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.
let result = x1.map((v,i)=>({"country":v, [name1]:y1[i], [name2]:y2[i]}))GHGin{'country': 'US', 'CO2': 1, 'GHG': 2}is not a typo?