javascript - return Object.keys in a map got undefined -
what's wrong loop below? want calculate total_count , return [total, total] after manipulation within map, got undefined.
my raw
data
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 } } }]
loop
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)
array#foreach
doesn't return anything, use array#map
, object.values
instead:
const x = raw.map(obj => { return object.values(obj.age_range).reduce((acc, item) => acc + item.total_count, 0) })
working example:
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)
Comments
Post a Comment