gpt4 book ai didi

javascript - 如何在 Javascript 中重新组合对象?

转载 作者:行者123 更新时间:2023-11-28 17:42:30 25 4
gpt4 key购买 nike

我有一个位置列表:

[
{
"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)
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 - 如何在 Javascript 中重新组合对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com