Skip to content
Advertisement

How to convert a javascript array of Objects from one format to another format?

I have an array of objects and want to convert it from one format to another format.

the initial array looks like:

  const data = [
    {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}},
    {name: 'Customer 2', value: {Oil: 59, Gas: 96, Retail: 86}},
    {name: 'Customer 3', value: {Oil: 50, Gas: 69, Retail: 50}}
  ]

how to convert it to a format like this?

  const data = [
    {channel: 'Oil', 'Customer 1':  55, 'Customer 2': 59, 'Customer 3': 50},
    {channel: 'Gas', 'Customer 1':  66, 'Customer 2': 96, 'Customer 3': 69},
    {channel: 'Retail', 'Customer 1':  56, 'Customer 2': 86, 'Customer 3': 50},
    
  ]

any help please?

Advertisement

Answer

You can populate an objected keyed off the value categories and add the relevant data.

  const data = [
    {name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}},
    {name: 'Customer 2', value: {Oil: 59, Gas: 96, Retail: 86}},
    {name: 'Customer 3', value: {Oil: 50, Gas: 69, Retail: 50}}
  ]

const output = Object.values(data.reduce((a, c) => {
  Object.keys(c.value).forEach(k => {
    a[k] = a[k] || {channel: k};
    a[k][c.name] = c.value[k];
  });
  return a;
}, {}));

console.log(output);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement