In this object, I want to print out an array in the form of [userName, skills]. I know that these objects don't have indexes. Is it possible to detect the skills property and only print out the value of that?
const users = {
Alex: {
email: 'alex@alex.com',
skills: ['HTML', 'CSS', 'JavaScript'],
age: 20,
isLoggedIn: false,
points: 30
},
Asab: {
email: 'asab@asab.com',
skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
age: 25,
isLoggedIn: false,
points: 50
},
Brook: {
email: 'daniel@daniel.com',
skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
age: 30,
isLoggedIn: true,
points: 50
}
}
I first tried the code below but there was an error that it cannot read properties of undefined (reading 0).
let userId = Object.keys(users); //(3) ['Alex', 'Asab', 'Brook']
for (let i = 0; i < userId.length; i++) {
let userSkills = users.userId[i].skills;
console.log(userId, userSkills);
}
Is it the only way that I check all the skills one by one like below?
console.log(users.Alex.skills);
console.log(users.Asab.skills);
console.log(users.Brooks.skills);
You're almost there -
for (let i = 0; i < userId.length; i++) {
let userSkills = users[userId[i]].skills;
console.log(userId[i], userSkills);
}
Use Bracket Notation instead of Dot Notation. Because all the time dot notation is not acceptable. Like - .number, .dependingValue, .anyCalculation, numericValue.something
Javascript mixes up decimal.
Read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
let userId = Object.keys(users); //(3) ['Alex', 'Asab', 'Brook']
userId.forEach(u=> {
console.log(users[u].skills);
});
As said in comments, you should use bracket notation.
Links:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
https://javascript.info/object
Also, you can use this to shorten your code:
userId.forEach(user => console.log(users[user].skills));
About array methods you can read here: