0

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.

2
  • Integer keys will be enumerated in ascending order. So, you can't create that string in that specific order Commented Feb 21, 2021 at 14:03
  • Order isn't important Commented Feb 21, 2021 at 14:06

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what am I missing with these ones? Input is still an object
Not sure I understand your question correctly, but I've changed the sample to include capturing the result and displaying it. If that doesn't answer your question, then please explain why you'd want 'input' to change?
2

When you get a string with JSON.stringify(), you can then replace characters you don't want:

JSON.stringify({4: 2, 6: 1, 3: 2}).replace(/["{} ]/g, '');

Comments

2

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.

Comments

0

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.

1 Comment

Why get 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.