首先,我是NodeJS和JavaScript的新手,所以非常感谢任何帮助。
我的目标是能够解析csv文件,以便我可以看到每月有多少用户登录。为了让我这样做,我使用了npm" CSVtoJSON"把csv文件转换为JSON格式。这是我从JSON文件中获得的,但有超过8000个条目。下面是一个片段。
[
{ date: '2015-04-09T19:30:22.213795+00:00',
'email address': '',
'full name': 'Canton Bashkin',
action: 'LoggedInActivity',
application: '',
project: '',
task: '',
'other email address': '',
'other full name': '',
description: 'Canton Bashkin logged in' },
{ date: '2015-04-08T00:34:42.261728+00:00',
'email address': '',
'full name': 'Sha Phad',
action: 'LoggedInActivity',
application: '',
project: '',
task: '',
'other email address': '',
'other full name': '',
description: 'Sha Phad logged in' },
{ date: '2015-04-07T23:31:32.559654+00:00',
'email address': '',
'full name': 'Canton Bashkin',
action: 'LoggedInActivity',
application: '',
project: '',
task: '',
'other email address': '',
'other full name': '',
description: 'Canton Bashkin logged in' },
{ date: '2015-04-07T23:31:02.408628+00:00',
'email address': '',
'full name': 'Sha Phad',
action: 'LoggedInActivity',
application: '',
project: '',
task: '',
'other email address': '',
'other full name': '',
description: 'Sneha Phadke logged in'}
]
我的代码:
//Converter Class
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
var allUsers = [];
//end_parsed will be emitted once parsing finished
function parseUsers() {
converter.on("end_parsed", function (jsonArray) {
for (var i = 0; i < jsonArray.length; i++) {
var users = jsonArray[i]['full name'];
if (jsonArray[i]['action'] === 'LoggedInActivity') {
if (users != 'SD Elements Support' && users != 'Karan Sharala' && users != 'Rick Bogans'
&& users != 'Kanal Bhatya' && users != 'Sanka Saja' && users != 'Kiiko Plash') {
allUsers.push(jsonArray[i]);
}
}
}
console.log(allUsers);
});
}
parseUsers();
//read from file
require("fs").createReadStream("log.csv").pipe(converter);
我很难找到解析JSON的最佳方法,因此我不会在数组中添加相同名称的重复项。如果我完全错误,请指出正确的方向。谢谢你们的帮助。
获得名字后,我需要将它们分成几个月,我不太清楚如何做到这一点。任何帮助将不胜感激!
答案 0 :(得分:0)
使用名为unique
的对象来跟踪已添加的字符串
var unique = Object.create(null); // empty object, no inheritance
for (var i = 0; i < jsonArray.length; i++) {
var users = jsonArray[i]['full name'];
if (jsonArray[i]['action'] === 'LoggedInActivity') {
if (!(users in unique)) { // not seen this `full name` before
unique[users] = allUsers.push(jsonArray[i]);
}
}
}
如果您觉得它更容易理解,可以将它与过滤器结合使用,在这个特定的例子中,它不是更清晰。一个非常大的数组也可能会使过滤器的功能开销成本太高。
var unique = Object.create(null);
allUsers = jsonArray.filter(function (e) {
if (e['action'] === 'LoggedInActivity' && !(e['full name'] in unique)) {
return unique[e['full name']] = true;
}
return false;
});