javascript - 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}
解决方案
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 }) )
推荐阅读
- java - 带有弹簧启动的自定义验证器,用于文件列表
- c++ - iOS 框架。具有相同名称的模板函数,链接器选择错误的函数?
- javascript - 堆叠条形图的 Y 比例域最小值/最小值不为零;X 轴溢出
- angular - 如何使用http客户端将文件与角度反应形式一起传递到后端?
- c# - 将 Json 嵌套到具有变量键名的对象类中
- firebase - FireBase 和 Firebase 存储 - 是否可以将文件上传到存储并将 url 记录到 FireBase
- javascript - jquery 和 fs 在角度电子应用程序中不能一起工作(使用 ngx-electron)
- vue.js - 带有 Conversion API 的 Facebook Pixel - 帮助跟踪相同的事件 ID
- html - 为什么 Chrome DevTools 显示相同大小的 SVG 元素但笔划宽度不同?
- docker - .Net Core Dockerized WebAPI 无法向 Eureka 服务器注册