Sharon Chai
Sharon Chai

Reputation: 517

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.

Upvotes: 0

Views: 50

Answers (2)

kapantzak
kapantzak

Reputation: 11750

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);

Upvotes: 0

Hassan Imam
Hassan Imam

Reputation: 22524

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);

Upvotes: 2

Related Questions