I'm trying to get a list of all users with the author.username
property. So that means access posts author, comments author, and commentReplies author. I want an returned array with a list of usernames.
expected output
["blankman", "blankman2", "barnowl", "barnowl2", "blankman3"]
the wrong output
["blankman", "blankman2blankman3", "barnowl2"]
This is how im doing it but i think im doing it wrong. as its not dynamic
const arr = [{
"id": 5,
"title": "buttercup",
"postContent": "dsdsfsfsfsfsfs",
"likedByMe": false,
"likeCounts": 0,
"userId": 1,
"createdAt": "2020-08-17T03:41:16.749Z",
"updatedAt": "2020-08-17T03:41:16.749Z",
"author": {
"username": "blankman",
"gravatar": "https://lh3.googleusercontent.com/a-/AOh14GiZAw_0UZmt7X0pJFSIv6ELQMd2nN41v0a-eKrN",
"bio": null
},
"Likes": [],
"Comments": [{
"id": 46,
"comment_body": "fsfsfsfsfsf",
"gifUrl": "",
"userId": 1,
"postId": 5,
"createdAt": "2020-08-18T04:46:08.946Z",
"updatedAt": "2020-08-18T04:46:08.946Z",
"commentReplies": [{
"id": 18,
"replyBody": "fsfsffsffsffsf",
"userId": 2,
"commentId": 46,
"postId": 5,
"createdAt": "2020-08-21T16:40:47.205Z",
"updatedAt": "2020-08-21T16:40:47.205Z",
"author": {
"username": "barnowl",
"gravatar": null,
"bio": null
}
}],
"author": {
"username": "blankman2",
"gravatar": "https://lh3.googleusercontent.com/a-/AOh14GiZAw_0UZmt7X0pJFSIv6ELQMd2nN41v0a-eKrN",
"bio": null
}
},
{
"id": 47,
"comment_body": "fsfsfsfsfsf",
"gifUrl": "",
"userId": 1,
"postId": 5,
"createdAt": "2020-08-18T04:46:08.946Z",
"updatedAt": "2020-08-18T04:46:08.946Z",
"commentReplies": [{
"id": 18,
"replyBody": "fsfsffsffsffsf",
"userId": 2,
"commentId": 46,
"postId": 5,
"createdAt": "2020-08-21T16:40:47.205Z",
"updatedAt": "2020-08-21T16:40:47.205Z",
"author": {
"username": "barnowl2",
"gravatar": null,
"bio": null
}
}],
"author": {
"username": "blankman3",
"gravatar": "https://lh3.googleusercontent.com/a-/AOh14GiZAw_0UZmt7X0pJFSIv6ELQMd2nN41v0a-eKrN",
"bio": null
}
},
],
"RePosts": [],
"RepostedByMe": false
}]
const findUsers = arr.reduce((acc, cv) => {
const users = [
...acc,
cv.author.username, // get first level author.username
cv.Comments.reduce((acc, cv) => acc.concat(cv.author.username), ""), // get comments author.username
cv.Comments.reduce((acc, cv) => cv.commentReplies.reduce((acc, cv) => acc.concat(cv.author.username), ""), "") // get comment replies author.username
]
return users
}, [])
console.log(findUsers)