将数组数组转换为对象数组的有效方法

时间:2018-08-12 07:14:54

标签: javascript arrays object

我有一个接受2个参数的函数: 数组 csvFields:

["id","name","age",...]

和另一个数组 csvRows 的数组,其中包含这些字段的数据:

 [["1", "john", "10"],["2", "Jane", "11"],["3", "John Doe", "12"],...]

此函数输出的是这样的对象数组:

[{id: "1", name: "john", age: "10"},{id: 2", name: "jane", age: "11"},{id: "3", name: "John doe", age: "12"}, ...]

这是函数:

const arrayOfArraysToArrayOfObjects = (csvFields, csvRows) => {
        const data = csvRows.map((row) => {
            let obj = {};
            csvFields.forEach((field, index) => {
                obj[field] = row[index];
            });
            return obj;
        });
        return data;
    };


    const csvFields = ["id","name","age"];
    const csvRows = [["1", "john", "10"],["2", "Jane", "11"],["3", "John Doe", "12"]];
    const data = arrayOfArraysToArrayOfObjects(csvFields, csvRows);
    console.log(data);

问题是,当涉及到具有很多行的大型csv文件时,此功能并不是很有效,并且变得非常慢。另外,不同的csv文件的字段可能会有所不同,这就是为什么我必须保持所有动态。

有什么方法可以使此功能更有效?

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

循环比方法快,请参见基准:  https://jsperf.com/my-test321321321

const arrayOfArraysToArrayOfObjects = (csvFields, csvRows) => {
  let res = []

  for (let arr of csvRows) {
    let obj = {}
    for (let i = 0; i < arr.length; i++) {
      obj[csvFields[i]] = arr[i]

    }
    res.push(obj)
  }

  return res;
};


const csvFields = ["id","name","age"];
const csvRows = [["1", "john", "10"],["2", "Jane", "11"],["3", "John Doe", "12"]];
const data = arrayOfArraysToArrayOfObjects(csvFields, csvRows);
console.log(data);

答案 1 :(得分:1)

一种可能的改进是仅对 large 数组(csvRows)进行一次迭代,而不是对 small 数组({{1 }})一次。另外,您可以改用csvRows循环,其循环开销比数组方法要少(但可读性较差),因此对于大文件来说可能会更有效:

for

答案 2 :(得分:1)

您可以使用Object.assign并散布单个键/值对象。

const
    arrayOfArraysToArrayOfObjects = (csvFields, csvRows) => 
        csvRows.map(row => Object.assign(...csvFields.map((k, i) => ({ [k]: row[i] })))),
    csvFields = ["id", "name", "age"],
    csvRows = [["1", "john", "10"], ["2", "Jane", "11"], ["3", "John Doe", "12"]],
    data = arrayOfArraysToArrayOfObjects(csvFields, csvRows);

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