[英]Javascript - Count first element of multi dimensional array
我有以下代码来提取唯一作者列表的 ID 和用户名。
let authorsList = await Poem.find({ 'author.id': {$nin: community.busAdmins}}).where('communities').equals(community._id).populate('authors').sort({"author.username": 1});
let uniqueAuthorsList = [];
authorsList.forEach(details => {
if(!uniqueAuthorsList.some(code => code.username == details.author.username)){
uniqueAuthorsList.push({username: details.author.username, id: details.author.id});
}
});
对于这些作者中的每一位,我想计算他们写了多少博客。 到目前为止,我有这个代码:
const counts = {};
uniqueAuthorsList.forEach((el) => {
counts[el] = counts[el] ? (counts[el] += 1) : 1;
});
console.log(counts);
但这只会返回:
{ '[object Object]': 7 }
如何仅使用数组的第一个元素(用户名)来计算记录,所以我可以返回这样的列表?
Dave: 4
Emily: 7
Mark: 2
创建时将计数放入uniqueAuthorsList
中。
let uniqueAuthorsList = [];
authorsList.forEach(details => {
let author = uniqueAuthorsList.find(code => code.username == details.author.username);
if (author) {
author.count++;
} else {
uniqueAuthorsList.push({
username: details.author.username,
id: details.author.id,
count: 1
});
}
});
您可能只想将uniqueAuthors
对象而不是数组。
let uniqueAuthors = {};
authorsList.forEach(details => {
if (uniqueAuthors[details.author.username]) {
uniqueAuthors[details.author.username].count++;
} else {
uniqueAuthors[details.author.username] = {
username: details.author.username,
id: details.author.id,
count: 1
};
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.