我正在从 API 接收数据,需要将其转换为具有分组属性的更扁平的格式。
在此示例中,我有一个具有不同轮胎属性的汽车品牌列表。我正在尝试将汽车品牌与每个可用的轮胎尺寸/宽度进行分组。如果两个属性都匹配,我需要合并记录。
回应
[
{
carMake: 'Ford',
tires: [
{
brand: 'Dunlap',
otherKey: 'aaa',
size: 33,
width: 12,
},
{
brand: 'Good Year',
size: 33,
width: 12,
},
{
brand: 'Continental',
size: 33,
width: 11,
},
{
brand: 'Pirelli',
size: 32,
width: 12,
}
]
},
{
carMake: 'Chevy',
tires: [
{
brand: 'Dunlap',
size: 33,
width: 12,
},
]
}
]
期望的结果
[
{
carMake: 'Ford',
otherKey: 'aaa',
brands: ['Dunlap', 'Good Year'],
size: 33,
width: 12,
},
{
carMake: 'Ford',
brands: ['Continental'],
size: 33,
width: 11,
},
{
carMake: 'Ford',
brands: ['Pirelli'],
size: 32,
width: 12,
},
{
carMake: 'Chevy',
brands: ['Dunlap'],
size: 33,
width: 12,
}
]
我尝试过的:
我尝试过使用 flatMap 和 reduce,但我只能完成第一级。不可否认,我不是最擅长操作 JS 形状的人,因为我主要使用基于 C 的语言。
apiResponse.flatMap(({carMake, tires}) => tires.map((tire) => ({ carMake, ...tire })));
[{
carMake: 'Chevy',
brand: 'Dunlap',
size: 33,
width: 12,
}]
最佳答案
const apiResponse = [{"carMake":"Ford","tires":[{"brand":"Dunlap",otherKey:'aaa',"size":33,"width":12},{"brand":"Good Year","size":33,"width":12},{"brand":"Continental","size":33,"width":11},{"brand":"Pirelli","size":32,"width":12}]},{"carMake":"Chevy","tires":[{"brand":"Dunlap","size":33,"width":12}]}]
const r = apiResponse.flatMap(({carMake,tires})=>
Object.values(
tires.reduce((a,{brand,size,width,...other})=>{
let k = [carMake, size, width].join();
a[k] ??= {carMake, brands: [], size, width};
(a[k] = {...a[k], ...other}).brands.push(brand);
return a
},{})
)
)
console.log(r)
关于javascript - 在 JavaScript 中创建扁平数组时,如何对匹配的嵌套数组子项进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74756045/