我有一个数组,它包含大量的二维数组:
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]
”和“类型”myArray[0][2]
等等。)
如何以所需的形式获取阵列?提前谢谢。
答案 0 :(得分:9)
json = myArray.map(function(x) {
return {
"s_id": x[0],
"t_id": x[1],
"type": x[2]
}
})
请注意,IE中不支持map< 9。
答案 1 :(得分:1)
尝试:
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);
}
答案 2 :(得分:0)
您可以destructure map
中的参数并使用Shorthand property names:
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)