如何将名称添加到未命名的JSON对象的数组?

所以我目前正在使用csvtojson为了转换一个CSV文件,以及,JSON,而我的代码是返回一个未命名的对象数组。 不过,我想要命名这些对象。 更具体地说,我想使用第一列的值来命名对象。

我的CSV文件看起来像这样:

名字,餐厅,食物名称,评论,价格

安德鲁,Clucky的鸡,鸡肉,这个三明治真棒,$ 9.99

米歇尔,字节,大汉堡,汉堡干得好,12.99美元

凸轮,Candyland,美味软糖,散装糖果,1.75美元的好价钱

我正在使用此代码并在节点中运行它:

// require the csvtojson converter class var Converter = require("csvtojson").Converter; //create a new converter object var converter = new Converter({}); //call the fromFile function which takes in the path to the csv file, as well as a callback function converter.fromFile("./restaurants.csv", function(err,result){ // if an error has occurred, then handle it if(err){ console.log("An error has occurred"); console.log(err); } // create a variable called json and store the result of the conversion var json = result; // log our json to verify it has worked console.log(json); }); 

哪个返回:

 [ { 'First Name': 'Andrew', 'Restaurant': 'Clucky's Chicken', 'Food Name': 'Chickenator', 'Comment': 'This sandwich is awesome', 'Price': '$9.99' }, { 'First Name': 'Michelle', 'Restaurant': 'Bytes', 'Food Name': 'Big Burger', 'Comment': 'Burger was too well done', 'Price': '$12.99' }, { 'First Name': 'Cam', 'Restaurant': 'Candyland', 'Food Name': 'Yummy Gummies', 'Comment': 'Good price for bulk candy', 'Price': '$1.75' } ] 

但是,我希望它能够更多地回复以下内容:

 [ Andrew : { 'Restaurant': 'Clucky's Chicken', 'Food Name': 'Chickenator', 'Comment': 'This sandwich is awesome', 'Price': '$9.99' }, Michelle : { 'Restaurant': 'Bytes', 'Food Name': 'Big Burger', 'Comment': 'Burger was too well done', 'Price': '$12.99' }, Cam : { 'Restaurant': 'Candyland', 'Food Name': 'Yummy Gummies', 'Comment': 'Good price for bulk candy', 'Price': '$1.75' } ] 

任何人有什么build议,我怎么能做到这一点?

做一个自定义的函数(因为你想将array转换成map )。

 function arrayToMap(array) { var map = {}; array.map( (element) => { var firstName = element['First Name']; delete element['First Name']; map[firstName] = element; } ); return map; } 

创build一个新的数组itemArray ,然后循环数组中的所有项目并将其推送到itemArray

 var itemArray = [] a.map(item => { firstName = item["First Name"]; delete item["First Name"]; itemArray[firstName] = item; }) console.log(itemArray); // <<<< you get the result here