通过我的函数从一组对象中获取值并将这些值写入csv文件的最佳方法是什么?
对象会像这样出现:
[ { objectTo:
{ employeeName: 'John',
employeeID: '234234',
DOB: '2333'},
employeeCurrent: true,
employeePast: false},
{ objectTo:
{ employeeName: 'Janet',
employeeID: '23423432',
DOB: '23333' },
employeeCurrent:true,
employeePast: false} ]
我希望在一个单元格上获取objects1.objectTo.employeeName, objects1.objectTo.DOB, objects1.employeeCurrent
之类的对象,但是将每个objectTo写入其自己的行中。
我尝试循环并使用for循环设置它,然后将值传递给writeFile但这不起作用。这样做的最佳方式是什么?
我也尝试使用库下划线给我值,但这也不起作用,只写出整个对象:
var objectsToFile = function(objectsTotal){
objectsTotal = _.values(objectsTotal, function(value) {
return value.objectTo.employeeName;
});
objectsTotal = _.values(objectsTotal, function(value) {
return value.employeeCurrent;
});
objectsTotal = _.values(objectsTotal, function(value) {
return value.employeePast;
});
writeFile('objectsTotalet.csv', util.inspect(objectsTotal), function(err) {
if (err) console.log(err);
});
};
CSV中的预期输出(objects1.objectTo.employeeName,objects1.objectTo.DOB,objects1.employeeCurrent):
John 2333是的 珍妮特23333真的
答案 0 :(得分:0)
let obj = [ { objectTo:
{ employeeName: 'John',
employeeID: '234234',
DOB: '2333'},
employeeCurrent: true,
employeePast: false},
{ objectTo:
{ employeeName: 'Janet',
employeeID: '23423432',
DOB: '23333' },
employeeCurrent:true,
employeePast: false} ]
const csvString = obj.map(item => {
return [item.objectTo.employeeName, item.objectTo.DOB, item.employeeCurrent]
}).join('\n')
console.log(csvString)
// John,2333,true
// Janet,23333,true
如果您希望它们位于同一行,只需使用','
代替'\n'
获得字符串后,可以使用fs
将其写入csv
文件