My object looks like this:
{4: 2, 6: 1, 3: 2}
I want to output a string like this:
4:2,6:1,3:2
I have tried first converting to an array and then using stringify, but that replaces the colon between key and values with a comma.
My object looks like this:
{4: 2, 6: 1, 3: 2}
I want to output a string like this:
4:2,6:1,3:2
I have tried first converting to an array and then using stringify, but that replaces the colon between key and values with a comma.
Same concept as Igor's answer, just a bit shorter:
const input = {4: 2, 6: 1, 3: 2};
const result = Object.entries(input).map(e => e.join(':')).join(',');
console.log(result);
And of course, your original map doesn't preserve ordering, so it's impossible to get it in the output.
Maybe something like this would work.
const input = {4: 2, 6: 1, 3: 2};
const result = Object.entries(input).map(([key, value]) => `${key}:${value}`).join();
console.log(result);
// -> "3:2,4:2,6:1"
Please note that key-value order in output is not guaranteed to be the same as in original object.
Something like this:
const object = {a:2, b:4, c:6, d:8};
let result = "";
const len = Object.keys(object).length;
Object.entries(object).forEach(([key, value], index) => {
if (index < len - 1){
result += key + ":" + value + ", ";
} else {
result += key + ":" + value;
}
});
console.log(result);
Edited.
Object.keys(object).length in every loop? If you access the third parameter in the forEach, it will return the entries array and you could just use that length: ([key, value], index, array) and index < array.length - 1. Or you could just assign Object.entries to a variable and use forEach in another line