[英]How to move specific key value inside another array object in javascript
I have array object obj
how to move particular key value store
inside another array items
in javascript.我有数组 object
obj
如何将特定键值store
移动到 javascript 中的另一个数组items
中。 I would like to know how to pass particular key value inside another array in javascript我想知道如何在 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 })
}
Expected Output预计 Output
[
{
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"}]
}
]
You are almost in the right direction, just few changes need to be done in your map
function to get expected output:您几乎朝着正确的方向前进,只需在
map
function 中进行一些更改即可获得预期的 output:
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);
You can use reduce
and forech
if you want to try a different approach如果您想尝试不同的方法,可以使用
reduce
和forech
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.