Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在ReactJS中合并/分组对象_Javascript_Arrays_Reactjs - Fatal编程技术网

Javascript 在ReactJS中合并/分组对象

Javascript 在ReactJS中合并/分组对象,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我有以下阵列: [{id:0,name:'Weight',option:'250'},{id:0,name:'Roast',option:'Medium'}] [{id:0,name:'Weight',option:'250'},{id:0,name:'Roast',option:'Light'}] 我需要将它们合并为以下内容: [{id:0,name:'Weight',options:['250']},{id:0,name:'Roast',options:['Medium','Lig

我有以下阵列:

  [{id:0,name:'Weight',option:'250'},{id:0,name:'Roast',option:'Medium'}]
  [{id:0,name:'Weight',option:'250'},{id:0,name:'Roast',option:'Light'}]
我需要将它们合并为以下内容:

[{id:0,name:'Weight',options:['250']},{id:0,name:'Roast',options:['Medium','Light']}]
我尝试嵌套一些循环,也尝试使用merge、push和spread操作符,但我无法解决它

result.forEach((att) => {
  let newoptions = [];
  console.log('att', att.attributes);
   att.attributes.forEach((id, idx) => {
     console.log('id', id);
     newoptions = [...newoptions, { option: id.option }];
     newAttr[idx] = { name: id.name, options: newoptions };
   });

});

我建议您对这两个数组进行concat,然后对其进行迭代。然后用以下方法减少项目:

constdata1=[{id:0,name:“Weight”,option:“250”},{id:0,name:“carast”,option:“Medium”}];
constdata2=[{id:0,名称:“Weight”,选项:“250”},{id:0,名称:“carast”,选项:“Light”}];
常量数组=[…数据1,…数据2];//海螺
const result=array.reduce((o,c)=>{
const exist=o.find(item=>item.id==c.id&&item.name==c.name);
如果(!存在){
常量选项=数组
.filter(item=>item.id==c.id&&item.name==c.name)
.map(item=>item.option);
o、 push({id:c.id,name:c.name,options:Array.from(newset(options))});
}
返回o;
}, []);

控制台日志(结果)使用
flat
forEach
。使用键
name
构建对象,并聚合值

const进程=(…数据)=>{
常数res={};
data.flat().forEach({name,option,id})=>{
res[name]??={name,id,options:[]};
!res[name].options.includes(option)和&res[name].options.push(option);
});
返回Object.values(res);
};
常数arr1=[
{id:0,名称:“权重”,选项:“250”},
{id:0,名称:“烤”,选项:“中等”},
];
常数arr2=[
{id:0,名称:“权重”,选项:“250”},
{id:0,名称:“烤”,选项:“轻”},
];
日志(进程(arr1,arr2))