我从 API 获取此数据:
let dataFromApi = [
{
// lots of other props
name: 'super cool place',
address: 'address of food place',
classification: 'food',
},
{
// lots of other props
name: 'name of tech place',
address: 'address of tech place',
classification: 'tech',
},
{
// lots of other props
name: 'name of clothes place',
address: 'address of clothes place',
classification: 'clothes',
},
{
// lots of other props
name: 'name of of another clothes place',
address: 'address of another clothes place',
classification: 'clothes',
},
{
// lots of other props
name: 'name of of another tech place',
address: 'address of another tech place',
classification: 'tech',
},
]
我想做的是创建一个新的对象数组,其中包含两件事:
名为
classification
的 Prop ;名为
elections
的 prop,它是一个对象数组,其中包含与分类 prop 匹配的所有场所。
意思是这样的:
let establishmentsArray = [
{
classification: 'food',
establishments: [
{
name: 'name of food place',
address: 'address of food place',
classification: 'food',
// rest of its props
},
// Lots of other food places places
],
},
{
classification: 'clothes',
establishments: [
{
name: 'name of clothes place',
address: 'address of clothes place',
classification: 'clothes',
// rest of its props
},
{
name: 'name of another clothes place',
address: 'address of another clothes place',
classification: 'clothes',
// rest of its props
},
// Lots of other clothes places
],
},
{
classification: 'tech',
establishments: [
{
name: 'name of tech place',
address: 'address of tech place',
classification: 'tech',
// rest of its props
},
{
name: 'name of another tech place',
address: 'address of another tech place',
classification: 'tech',
// rest of its props
},
// Lots of other tech places
],
},
]
感谢您提前提供的帮助!
最佳答案
看起来您正在尝试按单个字段进行分组,这是 array.reduce 的一个很好的用例:
let dataFromApi = [
{
// lots of other props
name: 'super cool place',
address: 'address of food place',
classification: 'food',
},
{
// lots of other props
name: 'name of tech place',
address: 'address of tech place',
classification: 'tech',
},
{
// lots of other props
name: 'name of clothes place',
address: 'address of clothes place',
classification: 'clothes',
},
{
// lots of other props
name: 'name of of another clothes place',
address: 'address of another clothes place',
classification: 'clothes',
},
{
// lots of other props
name: 'name of of another tech place',
address: 'address of another tech place',
classification: 'tech',
},
]
let output = dataFromApi.reduce((acc, cur) => {
let { classification, ...rest} = cur;
let prev = acc.find(x => x.classification === classification);
if(!prev) {
acc.push({classification, establishments: [cur]});
} else {
prev.establishments.push(cur);
}
return acc;
}, []);
console.log(output);
关于javascript - 如何将此 API 中的数据转换为由特定 prop 组织的对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71396332/