如何在Javascript中重组对象?

我的位置列表:如何在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()获得唯一值的城市阵列尝试。它并没有返回整个cityreturn 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。然后,如果您需要数组中的这些对象,则只需通过键调用映射。例如创建锁定以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)

以上是 如何在Javascript中重组对象? 的全部内容, 来源链接: utcz.com/qa/259010.html

回到顶部