I have an array of objects and want to convert it from one format to another format.
the initial array looks like:
JavaScript
x
5
1
const data = [
2
{name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}},
3
{name: 'Customer 2', value: {Oil: 59, Gas: 96, Retail: 86}},
4
{name: 'Customer 3', value: {Oil: 50, Gas: 69, Retail: 50}}
5
]
how to convert it to a format like this?
JavaScript
1
6
1
const data = [
2
{channel: 'Oil', 'Customer 1': 55, 'Customer 2': 59, 'Customer 3': 50},
3
{channel: 'Gas', 'Customer 1': 66, 'Customer 2': 96, 'Customer 3': 69},
4
{channel: 'Retail', 'Customer 1': 56, 'Customer 2': 86, 'Customer 3': 50},
5
6
]
any help please?
Advertisement
Answer
You can populate an objected keyed off the value categories and add the relevant data.
JavaScript
1
15
15
1
const data = [
2
{name: 'Customer 1', value: {Oil: 55, Gas: 66, Retail: 56}},
3
{name: 'Customer 2', value: {Oil: 59, Gas: 96, Retail: 86}},
4
{name: 'Customer 3', value: {Oil: 50, Gas: 69, Retail: 50}}
5
]
6
7
const output = Object.values(data.reduce((a, c) => {
8
Object.keys(c.value).forEach(k => {
9
a[k] = a[k] || {channel: k};
10
a[k][c.name] = c.value[k];
11
});
12
return a;
13
}, {}));
14
15
console.log(output);