convert CSV lines into Javascript objects

后端 未结 4 2080
感情败类
感情败类 2020-12-16 17:51

I have a simple csv file

people.csv:

fname, lname, uid, phone, address
John, Doe, 1, 444-555-6666, 34 dead rd
Jane, Doe, 2, 555-444-7777, 24 dead rd         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-16 18:50

    You can use lodash (or underscore) to help with this.

    var objects = _.map(arr, function(item){return item.split(',');});
    var headers = objects[0];
    objects.splice(0, 1); // remove the header line
    populatedObject = [];
    objects.forEach(function(item){
       var obj = _.zipObject(headers, item);
       populatedObject.push(obj);
    });
    

    The .zipObject method will match each header to each value in the items array and produce an object.

提交回复
热议问题