gpt4 book ai didi

javascript - 返回 Object.map 中的键未定义

转载 作者:行者123 更新时间:2023-12-01 03:12:18 25 4
gpt4 key购买 nike

我下面的循环有什么问题?我想计算total_count并在 map 中进行一些操作后返回[total,total],但我没有定义。

我的原始数据

const raw = [{
"device_info": {
"name": "cam1",
},
"age_range": {
"0-10": {
"age_range": "0-10",
"total_count": 15,
"male_count": 6,
"female_count": 9
},
"11-20": {
"age_range": "11-20",
"total_count": 11,
"male_count": 7,
"female_count": 4
},
"21-30": {
"age_range": "21-30",
"total_count": 922,
"male_count": 452,
"female_count": 470
}
}
}, {
"device_info": {
"name": "cam2",
},
"age_range": {
"0-10": {
"age_range": "0-10",
"total_count": 1,
"male_count": 1,
"female_count": 0
},
"11-20": {
"age_range": "11-20",
"total_count": 2,
"male_count": 0,
"female_count": 2
},
"21-30": {
"age_range": "21-30",
"total_count": 90,
"male_count": 58,
"female_count": 32
}
}
}]

循环

const x = raw.map(obj => {
return Object.keys(obj).forEach(key => {
let total = 0
if (key === 'age_range') {
total = Object.keys(obj.age_range).reduce((acum, innerKey) => {
return acum + obj.age_range[innerKey].total_count
}, 0)
console.log(total)
}
});
})

console.log('x', x)

https://jsfiddle.net/19m3f7fs/1

最佳答案

Array#forEach 不返回任何内容,请使用 Array#mapObject.values相反:

const x = raw.map(obj => {
return Object.values(obj.age_range).reduce((acc, item) => acc + item.total_count, 0)
})

工作示例:

const raw = [{
"device_info": {
"name": "cam1",
},
"age_range": {
"0-10": {
"age_range": "0-10",
"total_count": 15,
"male_count": 6,
"female_count": 9
},
"11-20": {
"age_range": "11-20",
"total_count": 11,
"male_count": 7,
"female_count": 4
},
"21-30": {
"age_range": "21-30",
"total_count": 922,
"male_count": 452,
"female_count": 470
}
}
}, {
"device_info": {
"name": "cam2",
},
"age_range": {
"0-10": {
"age_range": "0-10",
"total_count": 1,
"male_count": 1,
"female_count": 0
},
"11-20": {
"age_range": "11-20",
"total_count": 2,
"male_count": 0,
"female_count": 2
},
"21-30": {
"age_range": "21-30",
"total_count": 90,
"male_count": 58,
"female_count": 32
}
}
}]

const x = raw.map(obj => Object.values(obj.age_range).reduce((acc, item) => acc + item.total_count, 0))

console.log(x)

关于javascript - 返回 Object.map 中的键未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45752824/

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