将数组转换为对象数组

IT技术 javascript arrays name-value
2021-03-08 19:15:26

如何将数组转换为 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个回答

演示

使用您提供的数据:

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 }
]
赞成。使用两个 for 循环是最简单的解决方案,尽管我的方法map()更优雅,imo。
2021-05-08 19:15:26

如果同时使用 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 } 
]

一可避免两次迭代使用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/

对于那个很抱歉。不是故意的 :D
2021-04-20 19:15:26
@crush 你在那个测试中有点利用了我:jsperf.com/testing-map-foreach-vs-2x-for-statements/2但无论如何我的算法要慢得多。显然map()在 V8 和其他 JS 引擎中优化的空间
2021-04-28 19:15:26
绝对更优雅,我同意。不幸的是,它在 Chrome 31.0.1650 中慢了 160 倍(也许我设置的测试错了?我没想到)而且,map()本质上是一个封装的迭代,所以你仍然迭代两次。
2021-05-10 19:15:26
我试图用上述数据制作堆积面积图。但不知何故我无法理解如何将数据用于堆积条形数据。bl.ocks.org/mbostock/3885211
2021-05-14 19:15:26

破坏:

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)