数组到普通JS中的obj

时间:2017-01-20 20:36:24

标签: javascript arrays object

我有一个数组,需要通过组合键/值来创建一个对象。任何想法如何1.递归和2.没有递归 - 在没有任何外部库的普通JS中(如下划线,Lodash,......)

[
    [
        ['firstName', 'Eren'], ['lastName', 'Duran'], ['age', 22], ['role', 'admin']
    ],
    [
        ['firstName', 'Sallito'], ['lastName', 'Jordan'], ['age', 16], ['role', 'server']
    ]
]

应该成为:

  [
        {firstName: 'Eren', lastName: 'Duran', age: 22, role: 'admin'},
        {firstName: 'Sallito', lastName: 'Jordan', age: 16, role: 'server'}
    ]

1 个答案:

答案 0 :(得分:1)

您可以使用Array#mapArray#forEach的迭代方法。

var array = [[['firstName', 'Eren'], ['lastName', 'Duran'], ['age', 22], ['role', 'admin']], [['firstName', 'Sallito'], ['lastName', 'Jordan'], ['age', 16], ['role', 'server']]],
    result = array.map(function (a) {
        var object = {};
        a.forEach(function (b) {
            object[b[0]] = b[1];
        });
        return object;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }