r/code • u/OsamuMidoriya • Jun 26 '24
Help Please JS Object.keys()
Do you use Object.keys often?
Can you explain what's going on in this code what would be the key, index.
At first I was still thing they was object not arrays because that's what they looked like. I know the key was username1/2/3/ and the value is ben/kevin/deku but they don't have index and removing index from the parameters changed nothing, but arrays have index but not keys. from the cosole.log to get the key we console.log key, and to get the value its obj[key] but why?
I tried console.log(Object.keys(obj)) but that mad it more confusing because now the names(values) where gone and it was just an array of the username(keys)
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key, index) =>{
console.log(key, obj[key]);
})
// username1 ben
// username2 kevin
// username3 deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key) =>{
console.log(key, obj[key]);
})
// username1 ben
// username2 kevin
// username3 deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key, index) =>{
console.log(obj[key]);
})
// ben
// kevin
// deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key) =>{
console.log(key);
})
// username1
// username2
// username3
View all comments
Show parent comment
2
u/Adept-Result-67 Jun 27 '24 edited Jun 27 '24
Let’s say that you have an array of 50,000 customer orders, and you want to find a list of all the products that were ordered. It could be one product ordered 50,000 times, or it could be 50,000 different products ordered once each… or any combination between that.
We could write some code to do it like this
Your productIds would be something like this
I don’t quite understand your question 2 but i’m sure this will all ‘click’ for you in your brain soon and make sense.
Here’s an examples of when you might use it:
The first use case above, you know exactly where the piece of data you’re wanting to retrieve is, so you can use the dot notation to get it (glossary.ghi789.plural)
If glossary was an array…
This could be fine if the list is only 5 animals long, but consider how long and inefficient it would be to do this if the list was 500,000 animals, and sheep was 499,999 in the array. looping through the array would require you find 499998 incorrect matches before you found the correct value.