Iterate an object within another. Is it possible?

Asked

Viewed 206 times

-2

let myObject = {
        nome: 'Nome',
        idade: 20,
        endereco: {
            rua: 'Tal',
            numero: 5,
            municipio: {
                codigo: 1,
                ibge: '001'
            }
        }
    };

    Object.keys(myObject)
      .forEach((key) => {
         console.log(key);
         // 'nome', 'idade', 'endereco'
      });

I want to be able to make a given method, receive an object and be able to iterate all properties, even if they are chained. It is possible?

  • 4

    Hi Vitor, can you translate the question into English? Do you want to iterate internal properties recursively, is that it? which application do you want to achieve?

  • Yes, that’s right, Sergio. Basically this, I want a possible method to receive an object and be able to identify all property values, even if the parsing property carries another object, you know? I ended up sending in English without noticing that it was on the Portuguese page. It was bad.

2 answers

2


Check if the property is an object with prop instanceof Object or typeof prop === 'object', if it is, use recursiveness to iterate over the properties of that object as well.

let myObject = {
    nome: 'Nome',
    idade: 20,
    endereco: {
        rua: 'Tal',
        numero: 5,
        municipio: {
            codigo: 1,
            ibge: '001'
        }
    }
};

function iterar(obj) {
    for (let prop in obj) {
        console.log(prop);
        if (obj[prop] instanceof Object) {
            iterar(obj[prop]);
        }
    }
}

iterar(myObject);

Note: arrays are considered objects in Javascript, and will also enter the condition.

  • Thank you! This alternative did exactly what I needed ..

1

You need to create a function that checks whether a given object contains the key you are looking for and that if you have nested objects (or arrays) recursively traverse them by calling yourself.

A suggestion would be:

// Retorna null or object with `{value: xxx}`

const procuraChave = (obj, chave) => {
  const chaves = Object.keys(obj);

  if (chaves.includes(chave)) {
    return {value: obj[chave]};
  }
  
  for (let c of chaves) {
    if (typeof obj[c] === 'object') {
      return procuraChave(obj[c], chave);
    }
  }

  return null;
}

const teste = {
  produto: 'Meu produto',
  detalhes: {
    preco: {
      fabrico: 250,
      venda: 500
    }
  }
};

const precoVenda = procuraChave(teste, 'venda');
console.log('Preço de venda:', precoVenda);

  • Sergio, thank you very much! This solution also suits me, when I need to look for something specific inside the object.

Browser other questions tagged

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