简体   繁体   中英

Map the value of array of object into object properties

How do I make array of object value into object property? I want to turn this

const array = [
  {
    "age_group": [
      {
        "range": "0-20",
        "total_count": 100
      },
      {
        "range": "21-30",
        "total_count": 200
      },
    ],
    "machine": {
      "name": "SK2DS0011",
    }
  }
]

into this

[{name: "SK2DS0011", "0-20": 100, "21-30": 200}]

I'm stuck at using reduce.

temp_arr = ori.reduce((accum, arr, i) => {
  return accum['abc'] = arr.age_data.map(o => ({[o.range]: o.count}))
},{})

Maybe I'm using map wrong within my reduce.

You can use array#map to generate your array of object. For each age_group you can use array#map , spread syntax and Object.assign() to create the range and total_count object. You can use array_reduce to generate the sum of all ranges.

 const array = [{ "age_group": [{ "range": "0-20", "total_count": 100 }, { "range": "21-30", "total_count": 200 }, ], "machine": { "name": "SK2DS0011", } }], result = array.map(({age_group, machine}) => { const {name} = machine; const obj = Object.assign(...age_group.map(({range, total_count}) => ({[range] : total_count}))); const total = age_group.reduce((s,o) => s + +o.total_count, 0); return {name, ...obj, total}; }); console.log(result); 

Check this solution without using reduce . Instead use map to construct the new array:

 const arr = [ { "age_group": [ { "range": "0-20", "total_count": 100 }, { "range": "21-30", "total_count": 200 }, ], "machine": { "name": "SK2DS0011", } } ]; // Use map to format the new array with the desired properties let result = arr.map((x) => { // Get the 'name' property let obj = { name: x.machine.name, }; // Iterate over the 'age_group' array and add one property for each element var thisTotal = 0; for (var k in x.age_group) { let a = x.age_group[k]; obj[a.range] = a.total_count; // Add this range to total thisTotal += a.total_count; } // Add the 'total' property obj.total = thisTotal; // Return the final array return obj; }); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM