11

I have JSON array like this

var array= [{id:1,name:'foo'},{id:2,name:'bar'}]

I would like to add a new key (eg:isApproved) to each object in the existing array

expected output:

var array= [{id:1,name:'foo',isApproved:true},{id:2,name:'bar',isApproved:true}] 

I used the map function to achieve this

array.map(function(e,index){
     e.isApproved[index]= true
}

But this not worked for me

shamon shamsudeen
  • 5,466
  • 17
  • 64
  • 129

6 Answers6

21

You were really close. You do not need the index here. The map passes through every element of the array, so 'e' will be each object in your array.

var array= [{id:1,name:'foo'},{id:2,name:'bar'}];

array.map(function(e){
     e.isApproved = true;
});
          
console.log(array);
Cata John
  • 1,371
  • 11
  • 19
10

With this code, you wont mutate objects inside your array

const arr = [{id:1,name:'foo'},{id:2,name:'bar'}];
const mapped = arr.map(element => Object.assign(element, {isApproved: true})

More new approach would be using spread operator:

const arr = [{id:1,name:'foo'},{id:2,name:'bar'}];
const mapped = arr.map(element => ({isApproved: true ,...element}))

Snippet

const arr = [{id:1,name:'foo'},{id:2,name:'bar'}];
    const mapped = arr.map(element => ({isApproved: true ,...element}))


console.log(mapped)
Kasia
  • 1,665
  • 1
  • 10
  • 16
2

Try this, you don't need the index:

var array= [{id:1,name:'foo'},{id:2,name:'bar'}];

array.map(value => value.isApproved = true);
console.log(array)
David Ibl
  • 901
  • 5
  • 13
2

Use the actual item 'e' in the map

Map also gives you the facility to alter each element and return them in a new array. This can be useful if you do not want your current array to alter its state rather you need a modified form of the same array.

check this code:

var array= [{id:1,name:'foo'},{id:2,name:'bar'}];

var modifiedArray = array.map(function(e,index){
    return Object.assign({isApproved:true},e);
});

console.log(array);
console.log(modifiedArray);

Output:

//array
[{id: 1, name: "foo"},
{id: 2, name: "bar"}]

//modifiedArray
[{isApproved: true, id: 1, name: "foo"},
{isApproved: true, id: 2, name: "bar"}]
Muhammad Danial Iqbal
  • 1,546
  • 1
  • 9
  • 10
0

e[index] doesn't make sense since this index is meant for the array you are iterating.

Set the property directly to e

array.map(function(e,index){
     e.isApproved = true; 
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0
<script>

var array= [{id:1,name:'foo'},{id:2,name:'bar'}]
array.forEach(function(e,index){
     e.isApproved= true;
})
console.log(array);

</script>

You can use forEach instead of map.

Ininiv
  • 1,325
  • 7
  • 12
  • actually, its always better to use map, if you want to modify every element of given array – Kasia Mar 14 '18 at 09:30