将键值对插入由键值对组成的数组中


let a = [
{ title: coke, price: 10},
{ title: soda, price: 20},
{ title: lime, price: 30},
{ title: olive, price: 30},
]

这就是我想要的

let b = [
{ title: coke, price: 10, owner: 'Amy'},
{ title: soda, price: 20, owner: 'Amy'},
{ title: lime, price: 30, owner: 'Amy'},
{ title: olive, price: 30, owner: 'Amy'},
]

我的代码和它的工作!

a.map(data => {
return {
title: data.title,
price: data.price,
owner: 'Amy'
}
})

但如果a的长度超过一百万,那就更优雅快捷了?

谢谢你帮我!

您可以将正在迭代的对象扩展为一个新对象,再加上一个新键。

let a = [
{ title: 'coke', price: 10},
{ title: 'soda', price: 20},
{ title: 'lime', price: 30},
{ title: 'olive', price: 30},
]
console.log(
a.map(obj => ({ ...obj, owner: 'Amy' }))
);

还要注意,title值需要使用字符串分隔符。

您只需在映射中添加键即可。

a.map(data => {
data.owner = 'Amy';
return data;
})

这是一个代码沙盒:https://codesandbox.io/s/little-monad-iln5l?file=/src/index.js

您也可以使用Object.assign((

更新相同的阵列:

let a = 
[ { title: 'coke',  price: 10 } 
, { title: 'soda',  price: 20 } 
, { title: 'lime',  price: 30 } 
, { title: 'olive', price: 30 } 
] 
a.forEach(o=>Object.assign(o,{owner: 'Amy'}))
console.log('a =', a )
.as-console-wrapper {max-height: 100%!important;top:0}
但在这种情况下,更简单的是

a.forEach(o=>o.owner = 'Amy')

创建一个新阵列:

let a = 
[ { title: 'coke',  price: 10 } 
, { title: 'soda',  price: 20 } 
, { title: 'lime',  price: 30 } 
, { title: 'olive', price: 30 } 
] 
let b = a.map(o=>Object.assign({},o,{owner: 'Amy'})) // o stay unchanged
console.log('a=', a )
console.log('b=', b )
.as-console-wrapper {max-height: 100%!important;top:0}

最新更新