1

I have 2 different sets of arrays which are needed to be merged into an object

x1 = ['US', 'UK', 'China'];
y1 = [1,2,3];
name1 = 'CO2';

x2 = ['US', 'UK', 'China'];
y2 = [4,5,6];
name2 = 'GHG';

x1 and x2 are always the same.

My ideal result


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

I have tried to construct an object like this

var result = {};

x1.forEach(function (key,i) { result.country = key, result[name1] = y1[i] });

but it returns only the last value

{country: "China", CO2: 3}

And like this

x1.forEach((key, i) => result[key] = y1[i]);

But then the name is out of the play

And the whole thing should be dynamic which also makes additional problems, I cannot manually set values like I needed.

2
  • You could do something like this: let result = x1.map((v,i)=>({"country":v, [name1]:y1[i], [name2]:y2[i]})) Commented Dec 4, 2020 at 8:16
  • are you sure that the value of GHG in {'country': 'US', 'CO2': 1, 'GHG': 2} is not a typo? Commented Dec 4, 2020 at 8:31

4 Answers 4

4

const x1 = ['US', 'UK', 'China'];
const y1 = [1, 2, 3];
const name1 = 'CO2';

const x2 = ['US', 'UK', 'China'];
const y2 = [4, 5, 6];
const name2 = 'GHG';

const result = x1.map((country, index) => ({
  country,
  [name1]: y1[index],
  [name2]: y2[index]
}));

console.log(result);

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

Comments

1

I think you can try something like this, basically, we go through x1 and build the result with the corresponding data.

var result = {}
for(i = 0; i < x1.length; i++) {
  result[i] = {}
  result[i]["country"] = x1[i]
  result[i][name1] = y1[i]
  result[i][name2] = y2[i]
}

console.log(result)

Comments

1

You can do this like following(note : no need of variable x2)-

function createObj(x1,y1,y2, name1, name2){
  var obj1={},
         obj2={},
         obj3={};
  var result=[obj1, obj2, obj3];
  result.forEach((obj, i)=>{
    obj.country=x1[i];
    obj[name1]=y1[i];
    obj[name2]=y2[i];
  })

  return result;
  
}

In your code you are getting the last value only because every time inside the for each loop you override the values of the object

Comments

1

let x1=["US","UK","China"],y1=[1,2,3],name1="CO2",x2=["US","UK","China"],y2=[4,5,6],name2="GHG";

let result = x1.map((e,idx) => ({country:x1[idx],co2:y1[idx],GHG:y2[idx]}))

console.log(result)

Comments

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.