I am creating an admin panel.
For some reason, my code returns an error saying banned users does not exist even though it is in the Object. This confuses me alot and I dont know how to solve it. I got the error originally that says TypeError: Cannot read properties of undefined (reading 'forEach')
, and when I logged the key banned_users, it returns undefined. I even tried logging the data in the console after it, but it still has the key banned_users in it.
Here is my code that handles the response:
fetch('/admin_info')
.then(response => response.json())
.then(data => {
console.log(data)
data.admins.forEach((admin) => {
var list_admin = document.createElement('li');
if (admin != data.owner && admin != data.admin_username) {
list_admin.className = 'list_admin';
list_admin.onclick = function (){
remove_admin(admin)
}
}
list_admin.id = `admin_${admin}`;
if (admin == data.owner){
list_admin.innerText = `${admin} (Owner)`
}else{
list_admin.innerText = admin
}
admin_list.appendChild(list_admin);
});
})
//Problem Code
banned_users = data.banned_users
console.log(data.banned_users)
banned_users.forEach((user) => {
var banned_user = document.createElement('li');
banned_user.className = 'banned_user';
banned_user.innerText = user
banned_user.appendChild(banned_list)
//
})
.catch(error => {
error_display.style.display = 'block';
error_text.innerText = `Admin Panel failed to load: ${error}`;
});
}
This is the JSON it is receiving as a response:
"admin_username":"Username",
"admins":["Username1","Username2"],
"banned_users":{"test":{}},"owner":"Username"}
Does anyone have a solution to this issue?
Edit: I am also having an issue with saying data.banned_users or data["banned_users"] since it’s not getting the key from the JSON and returning undefined for some reason
2
Answers
Your
banned_users
is an Object. Objects don’t have aforEach
method, only Arrays do. Instead offorEach
, use a for … in loop.Does this code work? I don’t see
banned_list
referred to anywhere else. But the structure stands…In your response,
banned_users
is an Object. Objects do not have aforEach
method. Instead, you can try something like this: