0

Is there any way to do a for...in key values instanced object instead forEach? With forEach is easy for me but I'm looking for to do it with for...in.

I made this with for each:

function Person(fullName, gender, city) {
    this.fullName = fullName;
    this.gender = gender;
    this.city = city;
}

var person01 = new Person("Nancy", "Female", "Los Angeles");
var person02 = new Person("James", "Male", "New York");
var person03 = new Person("Lucia", "Female", "Santa Barbara");


//To do the loop
var persons = [
    {fullName: "Nancy", gender: "Female", city: "Los Angeles"},
    {fullName: "James", gender: "Male", city: "New York"},
    {fullName: "Lucia", gender: "Female", city: "Santa Barbara"},
]

function listNames(myObject) {

    persons.forEach(function(obj) {
        console.log(obj.fullName);  
    });
}

listNames(persons);
//Nancy, James, Lucia

This way works, but I need to understand how its works the for in.

Mamun
  • 66,969
  • 9
  • 47
  • 59
jaumeserr
  • 39
  • 1
  • 8

1 Answers1

0

Try the following:

for(var key in myObject){
  console.log(myObject[key].fullName);
}

Working Example:

function Person(fullName, gender, city) {
    this.fullName = fullName;
    this.gender = gender;
    this.city = city;
}

var person01 = new Person("Nancy", "Female", "Los Angeles");
var person02 = new Person("James", "Male", "New York");
var person03 = new Person("Lucia", "Female", "Santa Barbara");


//To do the loop
var persons = [
    {fullName: "Nancy", gender: "Female", city: "Los Angeles"},
    {fullName: "James", gender: "Male", city: "New York"},
    {fullName: "Lucia", gender: "Female", city: "Santa Barbara"},
]

function listNames(myObject) {
  for(var key in myObject){
    console.log(myObject[key].fullName);
  }
}

listNames(persons);
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    I wouldn't go for a 'for in-loop' here. Instead I would use 'for of', which loops directly over the values instead of the keys. Check https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa for the problem. – Teemoh Apr 22 '18 at 11:49
  • @Teemoh, but OP mentioned in the question that he want solution with `for in` – Mamun Apr 22 '18 at 11:51
  • Yeah i know, I just wrote the comment also at the question – Teemoh Apr 22 '18 at 11:51
  • Thanks to all! That’s perfect. Did you think it is necessary the array with the objects? Can I do this only with the variables? Can't I, isn't it? @Mamun – jaumeserr Apr 22 '18 at 11:54
  • [Don't use `for…in` enumerations on arrays!](https://stackoverflow.com/q/500504/1048572) – Bergi Apr 22 '18 at 12:48