使用另一个数组中的值转换所有数组键 [英] Transform all Array Keys with Values from another Array
本文介绍了使用另一个数组中的值转换所有数组键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多从csv文件生成的数组.在所有数组中,第一个数组对象是csv标头标题.请参见下面的示例:
I have many arrays, generated from a csv file. Of all the arrays, the first array object is the csv header titles. See example below:
因此,总而言之,第一个数组的值(即key = 0和value ="report_date")应替换所有后续数组的所有键.
So in summary, the first array's values (i.e, key = 0, and value = "report_date") should replace all the keys of the all the subsequent arrays.
因此,除了第一个数组之外,所有其他数组都需要进行这样的转换.
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"
推荐答案
这应该可以解决问题:
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);
请记住, shift
会修改源数组.由于此功能, data
变量确实得到了编辑.
Keep in mind that shift
modifies the source array. The data
variable does get edited as a result of this function.
这篇关于使用另一个数组中的值转换所有数组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文