我有一个地点列表:
[
{
"id": 1,
"name": "Location 1",
"city": {
"id": 7,
"name": "Phoenix",
}
},
{
"id": 2,
"name": "Location 2",
"city": {
"id": 7,
"name": "Phoenix",
}
},
{
"id": 3,
"name": "Location 3",
"city": {
"id": 11,
"name": "Los Angeles",
}
}
]
除此之外,我想创建一系列城市,每个城市都有来自该城市的位置。
示例结果:
[
{
"id": 7,
"name": "Phoenix",
"locations": [
// location objects from Phoenix (Location 1 and Location 2)
{
"id": 1,
"name": "Location 1",
"city": {
"id": 7,
"name": "Phoenix",
}
},
{
"id": 2,
"name": "Location 2",
"city": {
"id": 7,
"name": "Phoenix",
}
}
]
},
{
"id": 11,
"name": "Los Angeles",
"locations": [
// location objects from Los Angeles (Location 3)
{
"id": 3,
"name": "Location 3",
"city": {
"id": 11,
"name": "Los Angeles",
}
}
]
}
]
我尝试使用.map()
和.filter()
来获取城市的唯一值数组。它并没有为整个city
(return item.city
)返回唯一且不同的值,所以我只使用了name
属性(return item.city.name
),因为我没有&#39真的关心城市身份。我得到了一系列独特的城市名称:
var cities = data.map(function (item) {
return item.city.name;
}).filter(function (value, index, self) {
return self.indexOf(value) === index;
});
现在我不得不构建一个将位置列为每个城市的属性的数组。提前谢谢你......
答案 0 :(得分:2)
我首先创建一个对象,其中的键设置为城市的id。然后,如果您需要数组中的这些对象,您只需通过键调用map。例如,创建一个键入ID的对象:
var arr = [{"id": 1,"name": "Location 1","city": {"id": 7,"name": "Phoenix",}},{"id": 2,"name": "Location 2","city": {"id": 7,"name": "Phoenix",}},{"id": 3,"name": "Location 3","city": {"id": 11,"name": "Los Angeles",}}]
var obj = arr.reduce((a, c) => {
if (a[c.city.id]) a[c.city.id].push(c)
else a[c.city.id] = [c]
return a
}, {})
console.log(obj)

现在你有一个干净的对象,如果你想要一个数组,只需在键上添加一个地图:
var arr = [{"id": 1,"name": "Location 1","city": {"id": 7,"name": "Phoenix",}},{"id": 2,"name": "Location 2","city": {"id": 7,"name": "Phoenix",}},{"id": 3,"name": "Location 3","city": {"id": 11,"name": "Los Angeles",}}]
var obj = arr.reduce((a, c) => {
if (a[c.city.id]) a[c.city.id].locations.push(c)
else a[c.city.id] = {name: c.city.name, locations:[c]}
return a
}, {})
var arr_version = Object.keys(obj).map(k => Object.assign({id: k}, obj[k]))
console.log(arr_version)