0

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

nice but this too much destructing version make things hard to read.
0

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

3 Comments

you could explain this a bit more and not just dump code
possible to use functional technique?
what if I want to have a property call total and it sum up all the range?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.