gpt4 book ai didi

javascript - 如何按属性聚合嵌套的 JavaScript 对象?

转载 作者:行者123 更新时间:2023-12-04 00:55:17 24 4
gpt4 key购买 nike

我有以下 JavaScript 对象:

var example = [{
country: "US",
things: {
weather: 'cloudy'
}
},
{
country: "US",
things: {
resource: 'lead',
weather: 'sunny'
}
},
{
country: "MX",
things: {
weather: 'sunny'
}
},
{
country: "MX",
things: {
resource: 'gold',
weather: 'sunny'
}
},
{
country: "MX",
things: {
resource: 'copper'
}
},
]

我想通过聚合转换成这种格式。

var out = [{
country_code: 'US',
things: {
resource: ['lead'],
weather: ['cloudy', 'sunny']
}
},
{
country_code: 'MX',
things: {
resource: ['gold', 'copper'],
weather: ['sunny'],
}
}

]

我曾尝试研究使用 reduce 和 map 的组合,但无济于事。如果这个示例也可以作为数据操作的一般策略的起点,那么可能会或可能不会涉及数组方法的使用。

最佳答案

使用reduce 迭代对象来编译你的新对象,拼凑你想要的东西:

const example = [{
country: "US",
things: {
weather: 'cloudy'
}
},
{
country: "US",
things: {
resource: 'lead',
weather: 'sunny'
}
},
{
country: "MX",
things: {
weather: 'sunny'
}
},
{
country: "MX",
things: {
resource: 'gold',
weather: 'sunny'
}
},
{
country: "MX",
things: {
resource: 'copper'
}
},
]

const out = Object.values(
example.reduce((a, v) => {
if (!a[v.country]) {
a[v.country] = {
country_code: v.country,
things: {}
}
}

Object.entries(v.things).forEach(([key, value]) => {
if (!a[v.country].things[key]) {
a[v.country].things[key] = []
}

if (!a[v.country].things[key].includes(value)) {
a[v.country].things[key].push(value)
}
})

return a
}, {})
)

console.log(out)

关于javascript - 如何按属性聚合嵌套的 JavaScript 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55155169/

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