How to append strings to a string in a loop?

Viewed 204

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?

4 Answers

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

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

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);

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)

One more way to do it:

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

Related