Reputation: 420
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
Upvotes: 2
Views: 47
Reputation: 171698
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());
Upvotes: 0
Reputation: 73301
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));
Upvotes: 1
Reputation: 10396
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]);
}
Upvotes: 0