简体   繁体   English

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

[英]Transform all Array Keys with Values from another Array

I have many arrays, generated from a csv file. 我有很多从csv文件生成的数组。 Of all the arrays, the first array object is the csv header titles. 在所有数组中,第一个数组对象是csv标头标题。 See example below: 请参见下面的示例:

在此处输入图片说明

So in summary, the first array's values (ie, key = 0, and value = "report_date") should replace all the keys of the all the subsequent arrays. 因此,总而言之,第一个数组的值(即key = 0,并且value =“ report_date”)应替换所有后续数组的所有键。

So a transformation like this for all the arrays except the first. 因此,除了第一个数组外,其他所有数组都需要这样的转换。

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"

You could map the result with an object and delete the first item (with just the key/key in it). 您可以将结果与对象映射,然后删除第一项(仅包含键/键)。

 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; } 

This should do the trick: 这应该可以解决问题:

 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); 

Keep in mind that shift modifies the source array. 请记住, shift会修改源数组。 The data variable does get edited as a result of this function. 由于此功能, data变量确实得到编辑。

One other way of solving your problem is as follows; 解决问题的另一种方法如下:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM