0

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

1 Answer 1

2

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)

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

5 Comments

great solution @adiga .... please could you explain this line acc[country] ||= { country } i'm learning from answers :)
@Codenewbie It's using the Logical OR assignment and Shorthand property names. It's equivalent to acc[country] = acc[country] || { "country": country }. The goal is to create an accumulator object is like { US: { country: "US", 'CO2': 1 } }. If the accumulator object doesn't have US as key, add the key and set it to { country: 'US' }
@adiga Wow they are amazing and very handy, tysm for explaining gbu :) ... :)
@Codenewbie there are two more similar conditional assignment operators AND &&= and Nullish assignment ??=. So, let a = null; a ??= 'value' will assign a new value to a only if a is null or undefined.
@adiga just saw all of them bro :) thanks for mentioning .... so kind of you

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.