我有一个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
,而是通过单个操作使其更整洁,甚至可以提高性能/更快?
答案 0 :(得分:3)
当您打算在数组内保留相同的值时,不应该使用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)
答案 1 :(得分:0)
对于每个对象,您可以使用散布运算符重用旧对象的属性/值,然后将其他属性/值添加到该新对象文字中,从而创建一个新对象:
arr = arr.map(s => (
{...s, status : "dev", customer_id : customerId, email_nb : emailId}
));
答案 2 :(得分:0)
是的,例如这样:
arr.map(s => {
s["status"] = "dev";
s["customer_id"] = customerId;
s["email_nb"] = emailId;
return s;
});
始终牢记:
arr.map(x => x + 1);
这只是它的简写:
arr.map(x => {
return x + 1;
});
答案 3 :(得分:0)
此外,您不必为每个对数据所做的更改链接地图。在地图的回调主体中进行所有更改,然后返回该对象。
let data = arr.map(entry => {
entry["something"] = otherData["something"];
entry["something else"] = otherData["something-else"];
// etc. for all of the keys
// now the entry is entirely transformed, you can return it
return entry;
})