gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 23:03:24 25 4
gpt4 key购买 nike

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

我的 CSV 文件如下所示:

First Name, Restaurant, Food Name, Comment, Price

Andrew, Clucky's Chicken, Chickenator, This sandwich is awesome, $9.99

Michelle, Bytes, Big Burger, Burger was too well done, $12.99

Cam, Candyland, Yummy Gummies, Good price for bulk candy, $1.75

我正在使用这段代码并在 Node 中运行它:

// 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' } ]

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

最佳答案

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

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

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

关于javascript - 如何将名称添加到未命名的 JSON 对象数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46977227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com