How to Loop a Java Object

Asked

Viewed 93 times

-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)
})
  • 1

    This answers your question? How to navigate an object in javascript?

  • Why use an array as if it were an object?

  • 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 do casas.forEach(etc...) or simpler: for (let casa of casas) { console.log(casa.cor) etc }

2 answers

2

A possible solution would be:

Convert object to Array

let casas = Object.values(obj);

Scroll through the Array normally

casas.forEach((casa) => {
 console.log(casa.cor);
});

-5

Try this:

var listCasas = function () {
    for (var i = 0; i < obj.length; i++) {
        console.log(obj[i].cor + ' ' + obj[i].quartos);
    }
}

listCasas();
  • if the code is in a Function, it should not pass obj by parameter?

  • By the way, why create a function? And anonymous still, what is the gain in doing so? (in this case, none) - Anyway, with or without function, this code does not work, because objects do not have the atrict length (would work if it were an array) - see: https://ideone.com/5NF56s

Browser other questions tagged

You are not signed in. Login or sign up in order to post.