I am attempting to make a discord bot using discord.js (unrelated to this question) however when I tried to list the staff infractions that one user has, I keep getting all values returned as undefined. It works perfectly when a user has 1 infraction, but more than 1 returns undefined.
In my JSON File labeled "infractions.json"
[
{
"user": "1387128937182739182",
"reason": "test",
"punishment": "banned"
},
{
"user": "648314224174432267",
"reason": "Bad",
"punishment": "bad"
},
{
"user": "648314224174432267",
"reason": "testing bot",
"punishment": "lmao"
}
]
And in my js file
var id = //the inputted id
var myArray = fs.readFileSync("infractions.json");
var arr = JSON.parse(myArray)
let obj = arr.filter(o => o.user === id);
console.log(obj)
Logging the obj
variable results in this in the console
[
{
"user": "648314224174432267",
"reason": "Bad",
"punishment": "bad"
},
{
"user": "648314224174432267",
"reason": "testing bot",
"punishment": "lmao"
}
]
However when I use obj.user
, obj.reason
, or obj.punishment
it returns undefined.
If there is only one object where user is 648314224174432267
It works perfectly and the reason and punishment are listed.
If anyone can help it would be greatly appreciated!
3
Answers
The
obj
variable returns an array with the infractions of theuser
, in order to acces it you must specify where on the array you want to get the data (index).If you do:
obj[0]
you will get the first element of the array which is:You can make a for loop to check all the punishments and reasons of the users or a map.
The
filter()
method creates a new shallow copy of a portion of a givenarray
, filtering down by the passed condition. In your case, it will check for id’s. Therefore what you receiving is not an object but an array.You have an array of interaction objects, as your structure can be simplified to:
…so you need to loop through this array and test for the user ID to build your list of logged infractions.
This results in a list of infraction objects you can act against.