r/code • • 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
4 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/OsamuMidoriya Jun 28 '24

I played around with the code, but I will go over this until I get it thank you lastly

allTypes.map(function([key, value]) //you put key and value inside of [ ] because we are working with an array right?

...value, // the ... is to spread the array out I notice if you got rid of the all you see is value, but when you add them back it was less nested.
id:key, // this just gave the keys a name of id you could of also given the name product

this is an example of what people ordered from amazon

const orders = {
   John:{
      sock: 2,
      hat:1,
      pants:4,
   },
   Mike:{
      PS5:1,
      games:10,
      controlers:2,
   },
   Kevin:{
      book: 6,
      Pens: 15,
      Bag:1,
   },
   Kim:{
      soup:3,
      mask:100,
      cards:1000,
   }
   Ben:{
      book:30,
      ps5:2,
      mask:50,
      socks:20 
  }
}

const product = orders.entries 

product.map(function([id,values]){
if(values[0][1] > 10){
console.log(`order more ${vales}`)
}eles 
console.log("we have enough")


}) 

in this example we can check what product are really in high demand and order more so we don't run out