gpt4 book ai didi

javascript - 删除数组中对象中的重复键并聚合每个状态 Javascript 的总数

转载 作者:行者123 更新时间:2023-12-01 13:11:23 24 4
gpt4 key购买 nike

我有这个对象数组,我想在 NY 中添加计数但只打印一次 NY 的状态,如何删除重复的键而不是 if 语句中的核心“NY”?

Input

const cityPopulation = [
{ state: 'NJ', city: 'Jersey', count: 100 },
{ state: 'NY', city: 'NYC', count: 100 },
{ state: 'CA', city: 'SFO', count: 100 },
{ state: 'NY', city: 'Albany', count: 100 },]

Output

州计数:新泽西州:100
州计数:纽约州:200
州计数:CA:100

我的方法:


cityPopulation.forEach(state => {

if (state.state === 'NY') {
state.count += state.count
}

console.log(`Count for state: ${state.state}: ${state.count}`)

}
)

最佳答案

你可以用 Array#reduce 来做

const cityPopulation = [ { state: 'NJ', city: 'Jersey', count: 100 }, { state: 'NY', city: 'NYC', count: 100 }, { state: 'CA', city: 'SFO', count: 100 }, { state: 'NY', city: 'Albany', count: 100 },];


let res = Object.values(cityPopulation.reduce((acc, item) => {
if (acc[item.state]) {
acc[item.state].count = acc[item.state].count + item.count
} else {
acc[item.state] = item
}
return acc;
}, {}))

console.log(res)

关于javascript - 删除数组中对象中的重复键并聚合每个状态 Javascript 的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59692038/

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