我有数组对象obj
如何在JavaScript中移动特定键值store
到另一个数组items
中。 我想知道如何在javascript中传递另一个数组中的特定键值
var obj = [
{
id:1,
store: "10",
items: [{name:"sample1", total: 20}, {name:"sample2", total: 10}] // add store
},
{
id:1,
store: "11",
items: [{name:"sample3", total: 10}, {name:"sample4", total: 10}] // add store
}
]
function newarray(obj){
return obj.map(e=>...e,e.items.map(i=>{...i,store: e.store })
}
预期产出
[
{
id:1,
store: "10",
items: [{name:"sample1", total: 20, store: "10"}, {name:"sample2", total: 10, store: "10"}]
},
{
id:1,
store: "11",
items: [{name:"sample3", total: 10, store: "11"}, {name:"sample4", total: 10, store: "11"}]
}
]
您的方向几乎是正确的,只需在map
函数中做几个更改即可获得预期的输出:
null
var obj = [ { id:1, store: "10", items: [{name:"sample1", total: 20}, {name:"sample2", total: 10}] }, { id:1, store: "11", items: [{name:"sample3", total: 10}, {name:"sample4", total: 10}] }];
var result = obj.map(val=>(val.items = val.items.map(p=>({...p,store:val.store})), val));
console.log(result);
如果要尝试不同的方法,可以使用reduce
和forech
null
var obj = [
{
id:1,
store: "10",
items: [{name:"sample1", total: 20}, {name:"sample2", total: 10}]
},
{
id:1,
store: "11",
items: [{name:"sample3", total: 10}, {name:"sample4", total: 10}]
}
]
newob=obj.reduce((acc,curr)=>{
curr.items.forEach(x=>{
x.store=curr.store
})
return [...acc,{...curr}]
},[])
console.log(newob)