Skip to content
Advertisement

Javascript: How to reconstruct a nested object into another object?

I have the following nested object:

var test = {'a': {'name': 'CO2', 'x': ['US', 'UK', 'China'], 'y': [1,2,3]}, 
            'b': {'name': 'GHG', 'x': ['US', 'UK', 'China'], 'y': [4,5,6]}
           };

I have to dynamically iterate and get the ideal result:

[{'country': 'US', 'CO2': 1, 'GHG': 4},
{'country': 'UK', 'CO2': 2, 'GHG': 5},
{'country': 'China', 'CO2': 3, 'GHG': 6}]

I have already asked but it was the thing with arrays and I can’t get how to work with objects.

I can iterate and get an array of 2 objects but it is not what I needed

var traces = [];

Object.keys(test).forEach(function(key) { 
  var keys = test[key].x;
  var values = test[key].y;
  var name = test[key].name;


  var trace = keys.map((country, index) => ({
     country,
     [name]: values[index]

  }));

traces.push(trace);
});

Advertisement

Answer

You could reduce the values of the test object. Add each country as a key to the accumulator object and the object needed in the output as its value. Loop through each country in x and update the accumulator.

const test={a:{name:"CO2",x:["US","UK","China"],y:[1,2,3]},b:{name:"GHG",x:["US","UK","China"],y:[4,5,6]}},

    values = Object.values(test),
  
    group = values.reduce((acc, { name, x, y }) => {
      x.forEach((country, i) => {
        acc[country] ||= { country }
        acc[country][name] = y[i]
      })
      return acc
    }, {}),
    
    output = Object.values(group)

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