提问者:小点点

如何在javascript中移动另一个数组对象中的特定键值


我有数组对象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"}] 
  }
]


共2个答案

匿名用户

您的方向几乎是正确的,只需在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);

匿名用户

如果要尝试不同的方法,可以使用reduceforech

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)