Heyo, I'm coding on an Economy-System right now but I have a problem. I have to check if the user has data and if he doesn't have data create it. Here is what I've done:
if (UserJSON.user[message.author.id]) { //It doesn't detect the message.author.id
console.log("User Data already exists");
return;
} else {
const newUser = {
user: message.author.id,
stats: {
money: 0
}
}
UserJSON.push(newUser);
fs.writeFileSync("./data/users.json", JSON.stringify(UserJSON, null, 2));
}
The writing data function works perfectly as you can see down here in the users.json
[
{
"user": "654022997983756328",
"stats": {
"money": 0
}
},
{
"user": "917065319724507176",
"stats": {
"money": 0
}
}
]
The only problem is "check if the user has data" It doesn't detect
[message.author.id]
Someone told me to do
if (UserJSON.[message.author.id].user) {
but sadly it didn't work too. Can anyone help me here fix this issue?
That's because UserJSON is an array and you're trying to access the "user" prop in the if condition, which doesn't exist. You need to check if the UserJSON array contains an object which has "user" value of the condition. Try this:
if (UserJSON.find((userObject) => parseInt(userObject.user) === message.author.id)) { console.log("User Data already exists"); return; }