Rexford Rexford - 9 months ago 32
Javascript Question

Transform all Array Keys with Values from another Array

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:

enter image description here

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.

"report_date": "2014-01-07"
"description": "Cupidatat reprehenderit anim non irure aliqua irure veniam sint veniam velit aute elit."
"email": ""
"company": "Techtrix"
"status": "false"
"name/last": "Pennington"
"name/first": "Helene"

Answer Source

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 = {
  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.


Keep in mind that shift modifies the source array. The data variable does get edited as a result of this function.