Leviathan_the_Great
Leviathan_the_Great

Reputation: 448

How to get the property name when using a for...in loop

const dog = {
   id:1,
   name : "Henry",
   breed: "border-collie"
}

   for(let prop in dog){
      if(prop.name === id && typeof prop === "number"){
          console.log("this prop is ok!")
          continue
      }
      if(prop.name === name && prop === "Henry"){
          console.log("prop is ok!")
          continue
      }
      if(prop.name === breed && prop === "border-collie"){
          console.log("mucho bueno")
          continue
      }
      else{
        console.warn("prop could not be identified") 
        break
      }
   }

So what I have here is some code which is correct, I believe, except for the .name pseudo property. I want to cycle through the whole list of a dog's properties, but I also want to be able to check the names each of the dog's properties to make sure they are valid.

is there a way to do this in a for...in loop. if not, what else can I do in order to be able to cycle through the props and check the prop name?

Upvotes: 1

Views: 1591

Answers (2)

Attersson
Attersson

Reputation: 4866

for (key in dog)

This iterates the keys (id, name, breed).

Corresponding values will be dog[key].

Upvotes: 0

Ry-
Ry-

Reputation: 224913

prop is already the property name, as a string; the value would be dog[prop].

const dog = {
    id: 1,
    name: "Henry",
    breed: "border-collie"
}

for (let prop in dog) {
    if (prop === "id" && typeof dog[prop] === "number") {
        console.log("this prop is ok!")
        continue
    }
    if (prop === "name" && dog[prop] === "Henry") {
        console.log("prop is ok!")
        continue
    }
    if (prop === "breed" && dog[prop] === "border-collie") {
        console.log("mucho bueno")
        continue
    } else {
        console.warn("prop could not be identified") 
        break
    }
}

You can also use Object.entries to iterate over keys and values as pairs:

for (let [name, value] of Object.entries(dog)) {
    if (name === "id" && typeof value === "number") {
        console.log("this prop is ok!")
    } else if (name === "name" && value === "Henry") {
        console.log("prop is ok!")
    } else if (name === "breed" && value === "border-collie") {
        console.log("mucho bueno")
    } else {
        console.warn("prop could not be identified") 
        break
    }
}

Upvotes: 1

Related Questions