我在 Stack Overflow 上看到了很多关于这个主题的问题,但是,它们似乎都返回一个对象。 (不是我想要的)
我下面有一个数组;
const locations = [
{"city": "London", "district": "Brixton", "id": "Eue3uFjUHKi6wh73QZLX"},
{"city": "Manchester", "district": "Bury", "id": "QZiiUBgzZaJt2HcahELT"},
{"city": "London", "district": "Hackney", "id": "v2itdyO4IPXAMhIU8wce"}
]
我想根据
"city"
键将此数组映射到各个部分。
我的预期输出是;
[
{
city: "London",
data: [
{
city: "London",
district: "Brixton",
id: "Eue3uFjUHKi6wh73QZLX"
},
{
city: "London",
district: "Hackney",
id: "v2itdyO4IPXAMhIU8wce"
}
]
},
{
city: "Manchester",
data: [
{
city: "Manchester",
district: "Bury",
id: "QZiiUBgzZaJt2HcahELT"
}
]
}
]
我已经尝试过以下方法;
const groupedLocations = locations.reduce((groups, item) => {
const { city } = item;
if (!groups[city]) {
groups[city] = [];
}
groups[city].push(item);
return groups;
}, {});
但是,这返回一个对象而不是数组。
这是一个工作代码:
const groupedLocations = locations.reduce((groups, item) => {
const { city } = item;
let relatedGroup = groups.find((group) => group.city === city);
if (!relatedGroup) {
relatedGroup = { city, data: [] };
groups.push(relatedGroup);
}
relatedGroup.data.push(item);
return groups;
}, []);
reduce
returns 从其减速器函数返回的任何类型。在你的例子中,它是一个对象,这就是为什么你最后得到一个对象。data
列表中。
希望这有帮助,祝你好运!