我有一个像这样的数组:
var arr =
[
["Id", "0011900000YDtPXAA1"],
["Name", "account 50"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4450"],
["Id", "0011900000YDtPbAAL"],
["Name", "account 54"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4454"]
]
我需要每个子数组都是一个包含一个键值对的对象。
[
{"Id": "0011900000YDtPXAA1"},
{"Name": "account 50"},
...
]
我试过
var objArr = new Map(arr);
这会生成我需要的键值对,但将它们全部放在同一个对象中。如何获得一组由一个k-v对组成的较小对象?
答案 0 :(得分:3)
我会做类似的事情:
var arr = [
["Id", "0011900000YDtPXAA1"],
["Name", "account 50"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4450"],
["Id", "0011900000YDtPbAAL"],
["Name", "account 54"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4454"]
];
const newArr = arr.map(innerArr => ({[innerArr[0]]: innerArr[1]}));
console.log(newArr);
var arr = [
["Id", "0011900000YDtPXAA1"],
["Name", "account 50"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4450"],
["Id", "0011900000YDtPbAAL"],
["Name", "account 54"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4454"]
];
const newArr = arr.map(function (innerArr) { return {[innerArr[0]]: innerArr[1]}; });
console.log(newArr);
map()
方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。
答案 1 :(得分:0)
你可以使用传统的for循环来实现这个
var arr = [
["Id", "0011900000YDtPXAA1"],
["Name", "account 50"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4450"],
["Id", "0011900000YDtPbAAL"],
["Name", "account 54"],
["OwnerId", "005190000023IPPAA2"],
["Industry", "Manufacturing"],
["Phone", "312-552-4454"]
];
var arr2 = [];
for (var i = 0; i < arr.length; i++) {
var sub = {};
sub[arr[i][0]] = arr[i][1];
arr2.push(sub);
}
console.log(arr2);