对象的组数组由多个键
我是编程的新手,所以我需要一些帮助。 我有各种各样的对象。我需要对其进行排序,然后将其变成一系列物体,这些物体将包含关键城市,然后是领导者的一系列物体和一系列咖啡店。
let arr = [
{city: 'New York', boss: 'John', name: 'Caffe 1'},
{city: 'New York', boss: 'John', name: 'Caffe 2'},
{city: 'New York', boss: 'Ben', name: 'Caffe 3'},
{city: 'New York', boss: 'Ben', name: 'Caffe 4'},
{city: 'Washington', boss: 'Lisa', name: 'Caffe 5'},
{city: 'Washington', boss: 'Lisa', name: 'Caffe 6'},
{city: 'Washington', boss: 'Kate', name: 'Caffe 7'},
{city: 'Washington', boss: 'Kate', name: 'Caffe 8'},
{city: 'Los Angeles', boss: 'Joe', name: 'Caffe 9'}
]
我需要得到这样的东西。
let result = [
{city: 'New York',
boss:[
{
name: 'John',
caffes:[
{name: 'Caffe 1'},
{name: 'Caffe 2'}
]
},
{name: 'Ben',
caffes: [
{name: 'Caffe 3'},
{name: 'Caffe 4'}
]
}
]
},
{city: 'Washington',
boss:[
{
name: 'Lisa',
caffes:[
{name: 'Caffe 5'},
{name: 'Caffe 6'}
]
},
{name: 'Kate',
caffes: [
{name: 'Caffe 7'},
{name: 'Caffe 8'}
]
}
]
},
{city: 'Los Angeles',
boss:[
{
name: 'Joe',
caffes:[
{name: 'Caffe 9'},
]
},
]
},
]
我能做的最好的事情就是:
function sortData(data) {
let groups = [];
for (let element of data) {
let existingGroups = groups.filter((group) => group.city == element.city);
if (existingGroups.length > 0) {
existingGroups[0].city = element.city;
existingGroups[0].boss = element.boss;
} else {
let newGroup = {
city: element.city,
boss: element.boss
};
groups.push(newGroup);
}
}
return groups;
}
它使得:
[ { city: 'New York', boss: 'Ben' },
{ city: 'Washington', boss: 'Kate' },
{ city: 'Los Angeles', boss: 'Joe' } ]
但是我不知道如何使其更加复杂。
我尝试了多种方式,但是他们中的任何一个都无法帮助我。 我该怎么做?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
的确,这是一个非常直接的“群体”,就像在此重复我如何按键对象数组?。但是您的数据需要在第一个分组中通过
boss
在city
中进行另一个级别的分组。这是一个示例分组到对象中,迭代a 循环然后使用 nofollow noreferrer“>逻辑无效nullish nullish nullish tossment(?? =?=) 。首先,对于
city
,然后对city.boss
再次完成。最后,我们将” value() 结果作为结果,并映射它,以便也转换每个boss
对一个值数组对象。It's true that this is at its heart a very straight forward 'group by' as in this duplicate How can I group an array of objects by key?. But your data requires another level of grouping by
boss
within the first grouping bycity
.Here's an example grouping into an object, iterating each element in a
for...of
loop then retrieving or creating the relevant properties using logical nullish assignment (??=). This is done first for thecity
and then again for thecity.boss
. Finally the we take theObject.values()
of the grouped object as the result, and map over it in order to also convert eachboss
object to a an array of values.