2

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.

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

3 Answers 3

2

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.", "[email protected]", "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; }

Sign up to request clarification or add additional context in comments.

Comments

1

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. The data variable does get edited as a result of this function.

1 Comment

Not really concerned if source array is modified. Working. Thanks
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.