6

我有一个数组,其中包含大量二维数组:

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

我需要将此数组转换为以下形式的对象以将其作为 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]等等。)

如何获得所需形式的数组?提前致谢。

4

3 回答 3

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

请注意,IE < 9 不支持map 。

于 2013-01-18T11:28:20.210 回答
2

尝试:

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);
}
于 2013-01-18T11:27:54.153 回答
2

您可以解构参数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)

于 2019-08-15T19:31:33.703 回答