javascript - return object within a reduce function -


why result of x

[object object]12

can't return object in reduce function? know in map, filter can return object, not sure what's wrong code below.

const raw = [{    "device_info": {      "name": "nokia",      "device_id": "123"    },    "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      }      }  }, {    "device_info": {      "name": "iphone",      "device_id": "456"    },    "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      }    }  }]    const x = raw.map(obj => {    return object.values(obj.age_range).reduce((acc, obj2) => ({      total_count: acc + obj2.total_count,      device_id: obj.device_info.device_id    }), 0)  })    console.log('x', x)

no clue what's wrong, need help.

as explained you: in first iteration, acc contains 0, return object. in next iteration, acc contain object, , try add object new total_count. suggest this:

const x = raw.map(obj => {   // calculate total   const total_count = object.values(obj.age_range).reduce((acc, item) => acc + item.total_count, 0)   // construct object   return { total_count, device_id: obj.device_info.device_id } }) 

working example:

const raw = [{    "device_info": {      "name": "nokia",      "device_id": "123"    },    "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      }      }  }, {    "device_info": {      "name": "iphone",      "device_id": "456"    },    "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      }    }  }]    const x = raw.map(obj => {    const total_count = object.values(obj.age_range).reduce((acc, item) => acc + item.total_count, 0)    return { total_count, device_id: obj.device_info.device_id }  })    console.log('x', x)

jsfiddle here.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -