如何在Javascript中重新组合对象?
我有一份地点清单:如何在Javascript中重新组合对象?,javascript,jquery,Javascript,Jquery,我有一份地点清单: [ { "id": 1, "name": "Location 1", "city": { "id": 7, "name": "Phoenix", } }, { "id": 2, "name": "Location 2", "city": { "id": 7, "name": "Phoenix", } }, { "id": 3,
[
{
"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;
});
现在,我一直在构建一个数组,将位置列为每个城市的属性。提前感谢您…我将首先创建一个对象,其中的关键点设置为城市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)
否则a[c.city.id]=[c]
归还
}, {})
console.log(obj)
我首先创建一个对象,其中的键设置为城市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)
否则a[c.city.id]=[c]
归还
}, {})
console.log(obj)
您的预期结果不是有效的javascript。locations
应该是对象还是数组?@Mark\Mlocations
应该是对象数组。预期结果无效。locations
应该是一个对象还是一个数组?@Mark\Mlocations
应该是一个对象数组。谢谢,这正是我一直在尝试的。我将尝试破译这个解决方案的每一步,以便更好地理解它。谢谢,这正是我一直在尝试的。我将尝试破译这个解决方案的每一步,以便更好地理解它。