所以我现在正在使用csvtojson将csv文件转换为,好吧,json,我的代码返回一个未命名对象的数组。但是,我想要命名这些对象。更具体地说,我想使用第一列中的值来命名对象。
我的CSV文件如下所示:
名字,餐厅,食物名称,评论,价格
Andrew,Clucky's Chicken,Chickenator,这个三明治真棒,9.99美元
Michelle,Bytes,Big Burger,Burger做得太好了,12.99美元
Cam,Candyland,Yummy Gummies,散装糖果的好价格,$ 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' } ]
有人对我如何做到这一点有任何建议吗?
答案 0 :(得分:4)
制作自定义功能(因为您想将array
转换为map
)。
function arrayToMap(array) {
var map = {};
array.map(
(element) => {
var firstName = element['First Name'];
delete element['First Name'];
map[firstName] = element;
}
);
return map;
}
答案 1 :(得分:2)
创建一个新数组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