Hi,
I’ve been playing with for…in and I can’t figure out how to iterate through nested objects acting as properties of other objects. I’ve looked through the documentation and searched the forum but can’t find anything. Can a single loop iterate through an object and the object’s properties which also have properties? I’m attaching my attempt as a reference.
you could check if lasagne[consistsOf]
is an object, if it is an object, you could use another loop?
then you get something like:
for (let nestedeObject in lasagne[consistsOf])
Thanks for the reply, where should I put the second loop? Inside the first one? I’m totally lost here. The closest I came to what I meant to do was this
I can’t run code from a screenshot, please copy paste your code to the forum.
Oh, sure
let lasagne = {
cuisine: 'Italian',
ingredients: {
pasta: 'large sheets',
sauce: 'tomato, bechamel',
meat: 'minced'
},
'serve with': 'red wine',
instructions: {
cook() {console.log(`Cook ${ingredients}, put into layers, bake.`)}
},
cost: '$20'
};
for (let consistsOf in lasagne) {
console.log(`${consistsOf}: ${lasagne[consistsOf]}`)
for (let nestedObj in lasagne[consistsOf]) {
console.log(`${lasagne.consistsOf[nestedObj]}`)
}
};
not all properties have an object as value, so you will need to do some kind of condition here:
console.log(`${consistsOf}: ${lasagne[consistsOf]}`)
// check here if lasagne[consistsOf] is an object
if (condition){
for (let nestedObj in lasagne[consistsOf]) {
console.log(`${lasagne.consistsOf[nestedObj]}`)
}
}