JasonA JasonA - 4 months ago 8
Javascript Question

Javascript add same property to all objects in array

I am working in node without angular or underscore and am looking for an efficient plain javascript answer (perhaps avoiding loops). I have the following array of JSON objects:

object = [
{account:2423, user:1564},
{account:1235, user:1564}
]


I want to add the following to each array within the object:

username:"clientname"


So that it looks like this in the end:

object = [
{account:2423, user:1564, username:"clientname"},
{account:1235, user:1564, username:"clientname"}
]

Answer

Iterate over elements using Array#forEach and set username property.

var object = [{
  account: 2423,
  user: 1564
}, {
  account: 1235,
  user: 1564
}];

object.forEach(function(v) {
  v.username = 'clientname';
})

console.log(object);


Even you can use the simple for loop.

var object = [{
  account: 2423,
  user: 1564
}, {
  account: 1235,
  user: 1564
}];

for (var i = 0; i < object.length; i++) {
  object[i].username = 'clientname';
}

console.log(object);