javascript - 将多个数组 .map 合并为一个
问题描述
我有一组 javascript 对象
var arr = [
{
query_result_id: 25,
author_email: 'john@example.com'
},
{
query_result_id: 28,
author_email: 'eric@example.com'
},
]
我.map
用来在每个 javascript 对象上输入新值
arr
.map( s => s["status"] = "dev")
.map( s => s["customer_id"] = customerId)
.map( s => s["email_nb"] = emailId)
//and so on for about 10 new key/values
输出是:
var arr = [
{
query_result_id: 25,
author_email: 'john@example.com',
status: dev,
customer_id: 45,
email_nb: 45
},
{
query_result_id: 28,
author_email: 'eric@example.com',
status: dev,
customer_id: 78,
email_nb: 56
},
]
在 javascript 中是否可以不链接 10.map
而是一个单一的操作以使其更清洁,甚至可能更高性能/更快?
解决方案
当您打算在数组中保留相同的值时,您不应该使用 map。
map
旨在重新创建一个新数组,其值取决于源数组。你想要做的是对每个元素应用一个forEach
函数
这是使用 foreach 的方法:
let customerId = "customerId"
let emailId = "emailId"
var arr = [{query_result_id: 25,author_email: 'john@example.com'},
{query_result_id: 28,author_email: 'eric@example.com'}]
arr.forEach( s => {
s["status"] = "dev"
s["customer_id"] = customerId
s["email_nb"] = emailId
})
console.log(arr)
推荐阅读
- node.js - nodejs rest url中的模式匹配
- python - 从 sklearn 尝试“LeaveOneGroupOut”时收到 python 异常
- spotify-scio - 为什么在排空流式管道时会收到很多 None.get 异常?
- android - npm run android 不启动安卓应用
- c# - 如何使用表达式在 LINQ Select new 中分配属性
- ionic-framework - Ionic 4 modal 组件参数类型不正确
- sql - T-SQL INSERT - 其他列重复时增加值
- xmlhttprequest - Office 加载项:由于访问控制检查,XMLHttpRequest 无法加载 XXX
- json - 改造 2 - 获得响应 200,但列表为空
- ios - 如何只使用 Airpod 的麦克风而不停止其他应用正在播放的任何音乐?