-2
An object does not have the same behavior as an object during a Javascript loop.
That example:
let obj = {
casa1: {
cor: 'azul',
quartos: 2,
},
casa2: {
cor: 'vermelho',
quartos: 4,
},
}
Does not work the standard foreach:
obj.forEach((item) => {
console.log(item)
})
This answers your question? How to navigate an object in javascript?
– Ricardo Pontual
Why use an array as if it were an object?
– tvdias
Not directly related, but finally: when you have keys like "something 1", "something 2", etc., it is a sign that maybe you should use an array instead of an object: something like
let casas = [ {cor: 'azul', quartos: 2}, {cor: 'vermelho', quartos: 4} ]
- if all the elements represent houses, having the keys indicating "box N" becomes somewhat redundant, because the number of each house can simply be their position in the array. And as now you have an array, you can docasas.forEach(etc...)
or simpler:for (let casa of casas) { console.log(casa.cor) etc }
– hkotsubo