簡體   English   中英

二維數組到 object (JavaScript)

[英]2-dimensional array to object (JavaScript)

我有一個數組,其中包含大量二維 arrays:

var myArray = [
    [2260146,2334221,"copy"],
    [1226218,2334231,"copy"],
    [2230932,-1,"copy"],
    [2230933,-1,"copy"],
    [2230934,-1,"copy"]
]

我需要將此數組轉換為以下形式的 object 以將其作為 JSON 發送:

var json = [
  {
    "s_id": 2260146,
    "t_id": 2334221,
    "type": "copy"
  },
  {
    "s_id": 1226218,
    "t_id": 2334231,
    "type": "copy"
  },
  {
    "s_id": 12,
    "t_id": -1,
    "type": "copy"
  }
]

("s_id" 應該是myArray[0][0] 、 "t_id myArray[0][1]和 "type" myArray[0][2]等等。)

如何獲得所需形式的數組? 提前致謝。

json = myArray.map(function(x) {
    return {    
        "s_id": x[0],
        "t_id": x[1],
        "type": x[2]
    }
})

請注意,<9的IE中不支持地圖

嘗試:

var length = myArray.length,
    json   = [];

for ( var i = 0; i < length; i++ ) {
  var subArray = myArray[i],
      item = {
        s_id: subArray[0],
        t_id: subArray[1],
        type: subArray[2]
      };
   json.push(item);
}

你可以解構在參數map和使用速記屬性名稱

 const myArray=[[2260146,2334221,"copy"],[1226218,2334231,"copy"],[2230932,-1,"copy"],[2230933,-1,"copy"],[2230934,-1,"copy"]] const output = myArray.map(([s_id, t_id, type]) => ({ s_id, t_id, type })) console.log(output) 

如何從二維數組遍歷以下結構

weekearn,monthearn 是包含對象數組的變量。 我需要循環,因為我不知道產品的數量

          const stackdata = {          
    
                       datasets:[{
                         data: weekearn,
                         label: 'Product 1',
                         backgroundColor: 'rgb(255, 87, 51)',
                         borderColor: 'rgb(255, 99, 132)',            
                     },
                     {
                         data: monthearn,
                         label: 'Product 2',
                         backgroundColor: 'rgb(155, 87, 51)',
                         borderColor: 'rgb(255, 99, 32)',
                        
                     }
                 ]
             };

暫無
暫無

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

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