Skip to content
Advertisement

Add key value to an array elements in JS

I can’t add a key value pair to my array objects:

 const arr = [{'a' :1, 'b':2},{'a':2, 'b':4}]
 arr.map( item => {item.price = 1
 document.getElementById("body").innerHTML += 'a : '+ item.price + ' ' });
   

I want arr to be :

{'a' :1, 'b':2, 'price' : 1},{'a':2, 'b':4, 'price' : 1}

Advertisement

Answer

The map function doesn’t modify the array you do it to, it returns a new modified array. So you must assign the output to a variable. I would suggest reading a bit more how mapping arrays works on the MDN Docs.

Here’s how I would implement what you’re looking for:

const arr = [{'a' :1, 'b':2},{'a':2, 'b':4}];
const newarr = arr.map( item => ({ ...item, price: 1 }) )
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement