I have two distinct sets of arrays that need to be combined into an object.
x1 = ['US', 'UK', 'China'];
y1 = [1,2,3];
name1 = 'CO2';
x2 = ['US', 'UK', 'China'];
y2 = [4,5,6];
name2 = 'GHG';
The x1 and x2 arrays always contain the same values.
This is the desired outcome:
[{'country': 'US', 'CO2': 1, 'GHG': 2},
{'country': 'UK', 'CO2': 2, 'GHG': 5},
{'country': 'China', 'CO2': 3, 'GHG': 6}]
I attempted to construct the object like this:
var result = {};
x1.forEach(function (key,i) { result.country = key, result[name1] = y1[i] });
However, it only displays the last value:
{country: "China", CO2: 3}
I also tried the following approach:
x1.forEach((key, i) => result[key] = y1[i]);
In this case, the name is not included in the output.
The entire process should be dynamic, which poses additional challenges as I cannot manually assign values as needed.