Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript map function :add new key and value to object [duplicate]

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

like image 726
shellakkshellu Avatar asked Mar 14 '18 09:03

shellakkshellu


People also ask

Does map allow duplicate keys JavaScript?

Map Keys. Maps accept any data type as a key, and do not allow duplicate key values.

How do I add a key-value to an array of objects?

To add a key/value pair to all objects in an array: Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

Can a map key have multiple values JavaScript?

A Map data structure is a key/value store. A single key maps to a single value. So you must change the value if you want multiple: var myMap = new Map(); myMap.


1 Answers

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);
like image 122
Cata John Avatar answered Oct 22 '22 11:10

Cata John