将数组转换为对象数组

时间:2013-12-27 21:04:08

标签: javascript arrays name-value

如何将数组转换为JavaScript对象数组。

例如我有一个数组

data = [
    ["fruits","frozen","fresh","rotten"],
    ["apples",884,494,494],
    ["oranges",4848,494,4949],
    ["kiwi",848,33,33]
]

我想将其转换为名称值对。

例如,结果集合中的第一个对象是

 {"fruits": "apple", "frozen": 884, "fresh": 494, "rotten": 494}

以及其他数据。

4 个答案:

答案 0 :(得分:8)

DEMO

使用您提供的数据:

var data = [
    ["fruits","frozen","fresh","rotten"],
    ["apples",884,494,494],
    ["oranges",4848,494,4949],
    ["kiwi",848,33,33]
]

以下函数将数组的第一个元素视为对象属性的键。然后它将遍历其余元素,并使用这些键将它们转换为对象。最后,它将返回这些新对象的数组。

function convertToArrayOfObjects(data) {
    var keys = data.shift(),
        i = 0, k = 0,
        obj = null,
        output = [];

    for (i = 0; i < data.length; i++) {
        obj = {};

        for (k = 0; k < keys.length; k++) {
            obj[keys[k]] = data[i][k];
        }

        output.push(obj);
    }

    return output;
}

输出

[
    { fruits: 'apples', fresh: 494, frozen: 884, rotten: 494 },
    { fruits: 'oranges', fresh: 494, frozen: 4848, rotten: 4949 },
    { fruits: 'kiwi', fresh: 33, frozen: 848, rotten: 33 }
]

答案 1 :(得分:7)

如果同时使用map和reduce,解决方案将变得非常优雅:

var collection = [
    ["fruits","frozen","fresh","rotten"],
    ["apples",884,494,494],
    ["oranges",4848,494,4949],
    ["kiwi",848,33,33]
];

var keys = collection.shift();
collection = collection.map(function (row) {
    return keys.reduce(function (obj, key, i) {
      obj[key] = row[i];
      return obj;
    }, {});
});

输出:

[ 
  { fruits: 'apples', frozen: 884, fresh: 494, rotten: 494 },
  { fruits: 'oranges', frozen: 4848, fresh: 494, rotten: 4949 },
  { fruits: 'kiwi', frozen: 848, fresh: 33, rotten: 33 } 
]

答案 2 :(得分:6)

可以避免使用shift() + map() + forEach()进行两次迭代:

var data = [
    ["fruits","frozen","fresh","rotten"],
    ["apples",884,494,494],
    ["oranges",4848,494,4949],
    ["kiwi",848,33,33]
];

var collection = data.slice(); // make a copy
var keys = collection.shift();

collection = collection.map(function (e) {
    var obj = {};

    keys.forEach(function (key, i) {
        obj[key] = e[i];
    });

    return obj;
});

演示:http://jsfiddle.net/d7W76/2/

答案 3 :(得分:1)

破坏:

const data = [
    ["fruits","frozen","fresh","rotten"],
    ["apples",884,494,494],
    ["oranges",4848,494,4949],
    ["kiwi",848,33,33]
]
const titles = data[0]
const obj = data.slice(1).map(([fruits,frozen,fresh,rotten]) => ({ fruits,frozen,fresh,rotten }) )
console.log(obj)