Javascript 将对象数组转换为包含对象数组的数组
我有这样一个对象数组:Javascript 将对象数组转换为包含对象数组的数组,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我有这样一个对象数组: [{...}, {...}, {...}, {...}, {...}] { id: ... name: ... association: { id: ... } } [ [ { ... association { id: 1} }, { ... association { id: 1} } ], [ { ... association { id: 2 } } ] ] 对象如下所示: [{...}, {...}, {...}, {...},
[{...}, {...}, {...}, {...}, {...}]
{
id: ...
name: ...
association: {
id: ...
}
}
[ [ { ... association { id: 1} }, { ... association { id: 1} } ], [ { ... association { id: 2 } } ] ]
对象如下所示:
[{...}, {...}, {...}, {...}, {...}]
{
id: ...
name: ...
association: {
id: ...
}
}
[ [ { ... association { id: 1} }, { ... association { id: 1} } ], [ { ... association { id: 2 } } ] ]
我希望收集具有相同关联id的对象并获得如下数组:
[{...}, {...}, {...}, {...}, {...}]
{
id: ...
name: ...
association: {
id: ...
}
}
[ [ { ... association { id: 1} }, { ... association { id: 1} } ], [ { ... association { id: 2 } } ] ]
如何执行此操作?听起来像是在寻找一个函数,该函数将返回包含所提供关联id的对象数组
const data = [{...},{...},{...}]
const getByAssociationID = (source, id) => source.filter(obj => obj.association.id === id)
console.log(getByAssociationID(data, id))
这应该按照您的描述对数据进行分组
function groupByAssociation(data) {
return data.reduce((list, value) => {
let added = false;
list.forEach(group => {
if(group[0].association.id === value.association.id) {
group.push(value);
added = true;
}
});
if(!added) {
list.push([ value ]);
}
return list;
}, []);
}
使用
forEach
以association.id
键构建和对象,并累积值
const数据=[
{
id:1,
名称:“废话”,
协会:{
id:“a1”
}
},
{
id:2,
姓名:"富",,
协会:{
id:“a2”
}
},
{
id:3,
名称:“测试”,
协会:{
id:“a2”
}
}
];
const进程=数据=>{
常量obj={};
data.forEach(项=>{
const-aId=item.association.id;
const newItem=obj[aId]| |[];
newItem.push(item);
obj[aId]=新项目;
});
返回Object.values(obj);
};
console.log(进程(数据))
听起来像是在寻找一个函数,该函数将返回包含所提供关联id的对象数组?我只想在关联id属性中收集包含相同值的不同对象