0
\$\begingroup\$

Takes the first array in the array and uses that to set the properties of an array-object.

var _ = require("underscore");
function csvToObject(data){
  var header = data.shift();
  return _.map(data, function(row){
    var temp = {};
    _.each(row, function(cell, key){
      temp[header[key]] = cell;
    });
    return temp;
  });
}

I created a non-underscore dep version

function csvToObject2(data) {
  var header = data.shift();
  var alpha = [];
  for (var i = 0; i < data.length; i++) {
    var beta = {};
    for (var j = 0; j < data[i].length; j++) {
      beta[header[j]] = data[i][j];
    }
    alpha.push(beta);
  }
  return alpha;
};

They both performed the same in jsPerf. Thoughts?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You can also use built-in methods such as map and reduce. According to JSPerf they are as fast and the code is shorter, so you could potentially get rid of the Underscore dependency:

function csvToObject2(data) {
  return data.slice(1).map(function(xs) {
    return xs.reduce(function(acc, x, i) {
      acc[data[0][i]] = x
      return acc
    },{})
  })
}
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.