1

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?

1 Answer 1

1

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

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

2 Comments

Thank you! I guess I will then have to change individually each value for the newly created set?
@Rockasaurus, depends on several things. You can often map other array data into a current array. Or, you can perform calculations in the map, and just add those to each value. Hopefully that makes sense.

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.