Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
56
rated 0 times [  62] [ 6]  / answers: 1 / hits: 41578  / 6 Years ago, wed, march 14, 2018, 12:00:00

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


More From » arrays

 Answers
72

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);




[#54943] Sunday, March 11, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynd

Total Points: 470
Total Questions: 108
Total Answers: 120

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;