2

Hello everybody I have a short question about iteration in objects

Here's my code [https://jsfiddle.net/Ar2zee/9g91ouq6/]

var names = {
  first: 'Sasha',
  second: 'Andrey',
  third: 'Pasha',

  lastnames: {
    firstL: 'Oga',
    secondL: 'opa',
    thirdL: 'uka'
  },
}
for (var keys in names) {
  for (var newKeys in names.lastnames) {
    console.log(names.lastnames[newKeys]);
  }
}

My goal it's to log once all of the lastNAmes oga, opa, uka, right now my results is 4 times each of the last name can you please explain why it's 4 times right now and how to make once each of them

Thank you

3 Answers 3

1

You are using two loops. The outer loop iterates all of the names object keys, which are first, second, third and lastnames. As the inner loop iterates over the names.lastnames, each of them will get logged in each iteration of the outer loop. To do what you want, simply remove the outer loop:

for( var newKeys in names.lastnames){
    console.log(names.lastnames[newKeys]);
}

If you're using this in real world code, make sure to check for hasOwnProperty when using a for in loop:

for( var newKeys in names.lastnames){
    if (names.lastnames.hasOwnProperty(newKeys)) console.log(names.lastnames[newKeys]);
}

Sidenote:

If you just want to get all the values in names.lastnames, you could also use Object.values():

var names = {
  first: 'Sasha',
  second: 'Andrey',
  third: 'Pasha',

  lastnames: {
    firstL: 'Oga',
    secondL: 'opa',
    thirdL: 'uka'
  }
};

console.log(Object.values(names.lastnames));

Sign up to request clarification or add additional context in comments.

Comments

0

You just need one for loop:

var names = {
    first: 'Sasha',
    second: 'Andrey',
    third: 'Pasha',

    lastnames: {
        firstL: 'Oga',
        secondL: 'opa',
        thirdL: 'uka'
    },
}

for (var key in names.lastnames) {
    console.log(names.lastnames[key]);
}

Comments

0

In modern browsers or node can use Object.values() which returns an array.

var names = {
  first: 'Sasha',
  second: 'Andrey',
  third: 'Pasha',

  lastnames: {
    firstL: 'Oga',
    secondL: 'opa',
    thirdL: 'uka'
  }
}

console.log(Object.values(names.lastnames).join());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.