1

When I do the below, I get an empty string for some reason.

var jsObj2 = {
  "key1": "value3",
  "key4": "value4"
};

var c = '';
for (var key in jsObj2) {
  c.concat(key + ': ' + jsObj2[key]);
}

console.log(c);

What I would have hoped for where

key1: value3
key4: value4

Question

Can anyone explain why my attempt doesn't work, and how the NodeJS approach would be?

0

4 Answers 4

6

The string c is not modified in place, but returns a new string.

Use c = c.concat(key + ': ' + jsObj2[key]);

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

Comments

1

You have to assign concated value to a variable.

var jsObj2 = {
  "key1": "value3",
  "key4": "value4"
};

var c = '';
for (var key in jsObj2) {
  c = c.concat(key + ': ' + jsObj2[key]);
}

console.log(c);

Comments

1

prefer to use += operator

var jsObj2 = { key1: "value3"
             , key4: "value4"
             }
  , c      = ''
  , comma  = ''
  ;
for (var key in jsObj2)
  {
  c    += comma + key + ': ' + jsObj2[key]
  comma = ', '
  }
console.log(c)

or :

var jsObj2 = { key1: "value3"
             , key4: "value4"
             }
  , c = Object.entries(jsObj2)
              .map(([k,v])=>`${k}: ${v}`)
              .join(', ')
  ;
console.log(c)

Comments

1

One more way to do it:

const jsObj2 = {"key1": "value3", "key4": "value4"};
let str = Object.entries(jsObj2).join('').replace(/,/g, ': ');
console.log(str);

Comments

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.