Evgeny
Evgeny

Reputation: 107

Extending objects in array without redefining

I've got an array of objects

var myArray = [{'id':'1','value':'firstValue'},{'id':'1','value':'secondValue'}, etc.]

I want to be able to extend the array later on in the code, so that I will have

var myArray = [{'id':'1','value':'firstValue', 'anothervalue':'anotherFirstValue'},{'id':'1','value':'secondValue', 'anothervalue':'anotherSecondValue'}, etc.]

Is there a way to do it without redefining myArray?

Upvotes: 1

Views: 33

Answers (1)

KevBot
KevBot

Reputation: 18888

You can map the array, and add to each object:

var myArray = [{
  'id': '1',
  'value': 'firstValue'
}, {
  'id': '1',
  'value': 'secondValue'
}];

//later on
myArray = myArray.map(function(obj) {
  obj.anothervalue = 'anotherFirstValue';
  return obj;
});

console.log(myArray);

Upvotes: 1

Related Questions