I have array object obj
how to move particular key value store
inside another array items
in javascript. I would like to know how to pass particular key value inside another array in 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
[
{
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:
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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.