我的位置列表:如何在Javascript中重組對象?
[
{
"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
),因爲我並不真正在意城市ID。我的獨特的城市名稱的數組:
var cities = data.map(function (item) {
return item.city.name;
}).filter(function (value, index, self) {
return self.indexOf(value) === index;
});
現在我卡在構建陣列將列出位置爲每個城市的屬性。預先感謝您...
您的預計結果無效。 「位置」應該是一個對象還是一個數組? –
@Mark_M'locations'應該是一個對象數組。 – TommyZG