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

use*_*695 5 javascript csv json node.js

所以我目前正在使用 csvtojson 以便将 csv 文件转换为 json,并且我的代码正在返回一组未命名的对象。但是,我希望对这些对象进行命名。更具体地说,我想使用第一列中的值来命名对象。

我的 CSV 文件如下所示:

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

Andrew, Clucky's Chicken, Chickenator, 这个三明治很棒,9.99 美元

Michelle, Bytes, Big Burger, Burger 做得太好了,12.99 美元

Cam,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);
});
Run Code Online (Sandbox Code Playgroud)

返回:

[ { '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' } ]
Run Code Online (Sandbox Code Playgroud)

但我希望它返回更多的东西:

[ 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' } ]
Run Code Online (Sandbox Code Playgroud)

有人对我如何做到这一点有任何建议吗?

Ant*_*vić 4

创建一个自定义函数(因为您想转换array为 a map)。

function arrayToMap(array) {
  var map = {};

  array.map(
    (element) => {
      var firstName = element['First Name'];
      delete element['First Name'];
      map[firstName] = element;          
    }    
  );
  return map;
}
Run Code Online (Sandbox Code Playgroud)