String concatenation in a loop

take a look at this fiddle.
It has a loop that iterates through an object properties…these properties might be true or null.

In case they are true I want to construct a string that will be composed of the property names that are true.

If update is true then the string will be just update
if add is true ALSO then the string would be updateadd.

How I could achieve that?I tried using concat somehow but I could not do it.
This string is meant for the server(it will be sent w ajax)

The .concat() method does not modify the original string; instead it returns a new string which you assign to the variables upd and add, which you both immediately discard. Actually you might just append the values using +=, which is probably what you want… alternatively you might .reduce() the Object.keys() like so:

var value = Object.keys(originals).reduce(function (result, current) {
  if (originals[current]) {
    result += current
  }
  
  return result
}, '')

Here’s how you can get a concatenated string of true values.

var originals={};
originals.update=true;
originals.remove=true;
originals.add=null;

var str = Object.keys(originals)
    .filter(key => originals[key] === true)
    .join("");
console.log(str); // "updateremove"
1 Like

thx…that did it

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.