如何将Javascipt数组转换为对象?

时间:2019-05-29 05:36:50

标签: javascript arrays javascript-objects

我在Javascript中有一个数组数组,例如

[
    ["2019","abc","xyz"],
    ["2014","DEF","PQR"]
]

如何将上述数组转换为对象数组,如

[
    {
        date: 2019,
        name:abc,
        address:xyz
    },
    {
        date: 2014,
        name: DEF,
        address: PQR
    }
]

3 个答案:

答案 0 :(得分:2)

您可以使用Array.map

let arr = [["2019","abc","xyz"],["2014","DEF","PQR"]];
let result = arr.map(([data,name,address]) => ({data, name, address}));
console.log(result);

答案 1 :(得分:2)

您可以使用Array.map建立所需的格式,这里我是date, name, and address中每个数组的Destructuring元素,而不是返回带有这些key/value对的对象

let data =  [["2019","abc","xyz"],["2014","DEF","PQR"]]

let op = data.map(([date, name, address]) => ({date, name, address}))

console.log(op)

答案 2 :(得分:0)

一个简单的例程

var arr = [["2019","abc","xyz"],["2014","DEF","PQR"]];

var output = [];

arr.forEach(function(el){

    output.push({
        date: el[0],
        name: el[1],
        address: el[2]
    });
});

console.log(output)