0

For example, if we have the following object in javascript:

var person,
    property;
    
    person = {
        firstName: "John",
        lastName:"Doe",
        age: 50,
        eyeColor: "blue",
        hairColor: "black",
        profession: "doctor"
    }

How do I print out only the second and fourth property of this object with for-in and if-else?

Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
Monika
  • 9
  • 2
  • 3
    You may have a look of [Does JavaScript guarantee object property order?](https://stackoverflow.com/q/5525795/14032355) before asking this question. – ikhvjs Feb 24 '22 at 15:04
  • is it a school exercise? – Fabrizio Calderan Feb 24 '22 at 15:09
  • There's no guarantee that those properties will be in that order so talking about "second" and "fourth" is not really useful. Are there specific properties you need to access? – Andy Feb 24 '22 at 15:11
  • console.log(person.lastName), console.log(person.eyeColor) - you should not try to access object properties by their numerical index. – James Feb 24 '22 at 15:22

1 Answers1

-2

another way would be.

var person = {
    firstName: "John",
    lastName: "Doe",
    age: 50,
    eyeColor: "blue",
    hairColor: "black",
    profession: "doctor"
  }
  
  for(key in person){
    var index = Object.keys(person).indexOf(key);
    if(index === 1 || index === 3){
      console.log("Key:", key, ", Value:", person[key]);
    }
  }
Nelsongt77
  • 48
  • 1
  • 3