Add property to an array of objects

2019-01-22 18:00发布

问题:

I have an array of objects as shown below

Object {Results:Array[2]}
     Results:Array[2]
[0-1]
0:Object
       id=1     
       name: "Rick"
1:Object
       id=2     
       name:'david'

I want to add one more property named Active to each element of this array of Objects.

The final outcome should be as follows.

Object {Results:Array[2]}
     Results:Array[2]
[0-1]
0:Object
       id=1     
       name: "Rick"
       Active: "false"
1:Object
       id=2     
       name:'david'
       Active: "false"

Can someone please let me know how to achieve this.

回答1:

You can use the forEach method to execute a provided function once for each element in the array. In this provided function you can add the Active property to the element.

Results.forEach(function(element) { element.Active = "false"; });


回答2:

or use map

Results.map((obj) => {
    obj.Active = 'false';
    return obj;
})

Read the spec