khawarizmi
khawarizmi

Reputation: 732

Push an attribute to all JSON objects in an Array

In javascript, I have an array of JSON objects;

var myArr = [{'attr1':1, 'attr2':2}, {'attr1':3, 'attr2':4}, {'attr1':5, 'attr2':6}]

I want to add another attribute 'attr3' to ALL JSON OBJECTS in this array. How to achieve this without using a loop construct with myArr[x].attr3='val'?

My desired end result is;

[{'attr1':1, 'attr2':2, 'attr3':'val'}, {'attr1':3, 'attr2':4, 'attr3':'val'}, {'attr1':5, 'attr2':6, 'attr3':'val'}]

Upvotes: 0

Views: 137

Answers (2)

Stephen Quan
Stephen Quan

Reputation: 26139

You can also use Array#map() for editing every element in an array.

var myArr = [{ 'attr1': 1, 'attr2': 2 }, { 'attr1': 3, 'attr2': 4 }, { 'attr1': 5, 'attr2': 6 }];

myArr = myArr.map( function(e) {
    e.attr3 = 'val';
    return e;
} );

document.write("<pre>" + JSON.stringify(myArr, 0, 4) + "</pre>");

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386730

You can use Array#forEach() for iterating through the array.

var myArr = [{ 'attr1': 1, 'attr2': 2 }, { 'attr1': 3, 'attr2': 4 }, { 'attr1': 5, 'attr2': 6 }];

myArr.forEach(function (a) {
    a.attr3 = 'val';
});
document.write("<pre>" + JSON.stringify(myArr, 0, 4) + "</pre>");

Upvotes: 1

Related Questions