Reputation: 974
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.
Upvotes: 1
Views: 57
Reputation: 4217
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)
Upvotes: 1
Reputation: 587
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
Upvotes: 1
Reputation: 226
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)
Upvotes: 1
Reputation: 4173
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);
Upvotes: 4