这里有很多这样的问题,但是我找不到满足我需求的问题。我正在寻找一个相对简单的解决方案,该解决方案是如何基于键将数组中的对象堆叠到新数组中。在示例数据中,我们通过“ ship”键将对象分组。原始数据: var myObjArray = [ { name:'Malcolm Reynolds', ship:'Serenity' }, { name: 'Carmen Ibanez', ship: 'Rodger Young', }, { name: 'Zander Barcalow', ship: 'Rodger Young', }, { name:'Hoban Washburne', ship:'Serenity' }, { name:'James Kirk', ship:'USS Enterprise' }];重组数据: var myNewObjArray = [ [{ name:'Malcolm Reynolds', ship:'Serenity' }, { name:'Hoban Washburne', ship:'Serenity' }], [{ name: 'Carmen Ibanez', ship: 'Rodger Young', }, { name: 'Zander Barcalow', ship: 'Rodger Young', }], { name:'James Kirk', // optionally also stick in an array ship:'USS Enterprise' }];如果有人对此有解决方案,我将不胜感激,至少可以说,我目前的尝试是草率的。
3 回答
慕容708150
TA贡献1831条经验 获得超4个赞
查找并删除重复的船舶名称,然后为每艘船舶查找人员。
const myObjArray = [
{
name:'Malcolm Reynolds',
ship:'Serenity'
},
{
name: 'Carmen Ibanez',
ship: 'Rodger Young',
},
{
name: 'Zander Barcalow',
ship: 'Rodger Young',
},
{
name:'Hoban Washburne',
ship:'Serenity'
},
{
name:'James Kirk',
ship:'USS Enterprise'
}
];
const ships = myObjArray.map(({ship}) => ship).filter((ship, i, arr) => arr.indexOf(ship) === i);
const personnelArray = ships.map(ship => myObjArray.filter(entry => entry.ship === ship));
console.log(personnelArray);
添加回答
举报
0/150
提交
取消