首页 > 解决方案 > 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}

标签: javascript

解决方案


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

推荐阅读