Skip to content Skip to sidebar Skip to footer

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: So in summary, the first array's values (i.e,

Solution 1:

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

Solution 2:

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 keysvar result = data.map(function(row) {
  var current = {};            // Create a new elementfor (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. The data variable does get edited as a result of this function.

Solution 3:

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

Post a Comment for "Transform All Array Keys With Values From Another Array"