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
Map Keys. Maps accept any data type as a key, and do not allow duplicate key values.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With