How would I access the following json data
"users":{
"2211392761":{"username":"user1"},
"14300995184":{"username":"user2"},
"2781554712":{"username":"user3"},
"3554341":{"username":"user4"},
"202611":{"username":"user5"},
"17754300653761":{"username":"user6"}
}
I have this so far and I am aware it is completely wrong:
Object.keys(jsonevents["events"]).forEach(function(key) {
if(eventName == jsonevents["events"][key]["name"]){
if(jsonevents["events"][key]["users"]){
if(jsonevents['events'][key]["users"][message.author.id]){
delete jsonevents['events'][key]["users"][message.author.id];
fs.writeFile(eventsjson, JSON.stringify(jsonevents),'utf8');
sayMessage += "```User is no longer part of the event "+jsonevents['events'][key]["name"]+"```";
} else {
sayMessage += "```user is not in the event "+jsonevents['events'][key]["name"]+"```";
}
} else {
sayMessage += "```Why do we have no users```";
}
} else {
//sayMessage += "```No event found```";
}
});
I need to be able to access the key by passing in the username, so user2 would give me 14300995184 so i can then use this to remove the user from the event.
You can search through the Object.entries with find() and return the right object. It will return an array of key/value the key will be what you're after:
let users = {
"2211392761":{"username":"user1"},
"14300995184":{"username":"user2"},
"2781554712":{"username":"user3"},
"3554341":{"username":"user4"},
"202611":{"username":"user5"},
"17754300653761":{"username":"user6"}
}
let found = Object.entries(users).find(([key, value]) => value.username === "user2")
console.log(found && found[0]) // found is undefined if not found
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With