Add property to an array of objects

Patrick picture Patrick · Aug 12, 2016 · Viewed 139.3k times · Source

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.

Answer

sidonaldson picture sidonaldson · Jun 7, 2017

or use map

Results.map(obj=> ({ ...obj, Active: 'false' }))

Edited to reflect comment by @adrianolsk to not mutate the original and instead return a new object for each.

Read the spec