Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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
    },{})
  })
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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