使用另一个数组中的值转换所有数组键

时间:2016-11-08 14:23:30

标签: javascript arrays

我有很多数组,都是从csv文件生成的。在所有数组中,第一个数组对象是csv标题标题。见下面的例子:

enter image description here

总而言之,第一个数组的值(即key = 0和value =" report_date")应该替换所有后续数组的所有键。

对于除第一个之外的所有数组,这样的转换。

Array[7]
"report_date": "2014-01-07"
"description": "Cupidatat reprehenderit anim non irure aliqua irure veniam sint veniam velit aute elit."
"email": "helene.pennington@techtrix.biz"
"company": "Techtrix"
"status": "false"
"name/last": "Pennington"
"name/first": "Helene"

3 个答案:

答案 0 :(得分:2)

您可以将结果映射到一个对象并删除第一个项目(只包含其中的键/键)。



var array = [["report_date", "description", "email", "company", "status", "name/last", "name/first"], ["2014-01-07", "Cupidatat reprehenderit anim non irure aliqua irure veniam sint veniam velit aute elit.", "helene.pennington@techtrix.biz", "Techtrix", "false", "Pennington", "Helene"]],
    result = array.map(function (a, _, aa) {
        var object = {};
        aa[0].forEach(function (key, i) {
            object[key] = a[i];
        });
        return object;
    }).slice(1);

console.log(result);

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




答案 1 :(得分:1)

这应该可以解决问题:



var data = [['id', 'name', 'value'], [0, 'foo', true], [2, 'bar', false], [3, 'baz', null], [4, 'foobar', undefined] ];

var keys = data.shift();       // Get the first row, containing the keys
var result = data.map(function(row) {
  var current = {};            // Create a new element
  for (var i = 0; i < keys.length; i++) {
    current[keys[i]] = row[i]; // Map the current row to keys on the new element
  }
  return current;              // Return the new element, to be used in the result.
});

console.log(result);
&#13;
&#13;
&#13;

请记住shift修改了源数组。由于此函数,data变量会被编辑。

答案 2 :(得分:0)

解决问题的另一种方法如下:

var data = [["prop_0", "prop_1", "prop_2"],
            ["val_00", "val_01", "val_02"],
            ["val_10", "val_11", "val_12"],
            ["val_20", "val_21", "val_22"]],
 newData = data.slice(1)
               .map(vs => vs.reduce((p,c,i) => i-1 ? Object.assign(p,{[data[0][i]]: c})
                                                   : Object.assign({},{[data[0][i-1]]: p, [data[0][i]]: c})));
console.log(newData);