簡體   English   中英

Javascript:如何從幾個 arrays 和變量構造 object?

[英]Javascript: How to construct an object from several arrays and variables?

我有 2 組不同的 arrays 需要合並到 object

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

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

x1 和 x2 始終相同。

我的理想結果


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

我試圖構建一個像這樣的 object

var result = {};

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

但它只返回最后一個值

{country: "China", CO2: 3}

像這樣

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

但是后來這個名字就出戲了

整個事情應該是動態的,這也會產生額外的問題,我不能像我需要的那樣手動設置值。

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

我認為您可以嘗試這樣的事情,基本上,我們通過x1 go 並使用相應的數據構建結果。

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)

您可以這樣做(注意:不需要變量 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;
  
}

在您的代碼中,您僅獲得最后一個值,因為每次在 for each 循環中您都會覆蓋 object 的值

 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM