我在Stack Overflow上看到了许多关于这个主题的问题,然而,它们似乎都返回了单个对象.(不是我想要的)
我下面有一个数组;
const locations = [
{"city": "London", "district": "Brixton", "id": "Eue3uFjUHKi6wh73QZLX"},
{"city": "Manchester", "district": "Bury", "id": "QZiiUBgzZaJt2HcahELT"},
{"city": "London", "district": "Hackney", "id": "v2itdyO4IPXAMhIU8wce"}
]
我想将此数组映射为基于"city"
键的部分.
我的预期yields 是;
[
{
city: "London",
data: [
{
city: "London",
district: "Brixton",
id: "Eue3uFjUHKi6wh73QZLX"
},
{
city: "London",
district: "Hackney",
id: "v2itdyO4IPXAMhIU8wce"
}
]
},
{
city: "Manchester",
data: [
{
city: "Manchester",
district: "Bury",
id: "QZiiUBgzZaJt2HcahELT"
}
]
}
]
我已经try 了下面的方法;
const groupedLocations = locations.reduce((groups, item) => {
const { city } = item;
if (!groups[city]) {
groups[city] = [];
}
groups[city].push(item);
return groups;
}, {});
但是,这返回的是对象而不是array.