Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
How to access object's name property

Consider a const that holds an object with multiple levels like this:

const test = {
  One: {
    a: 220,
    b: ['Chipotle', 'Subway', 'Habit Burger'],
  },
  Two: {
    a: 110,
    b: ['Chipotle'],
  },
  Three: {
    a: 200,
    b: ['Subway', 'Jack In The Box'],
  },
  Four: {
    a: 460,
    b: ['Chipotle', 'Subway', 'Habit Burger', 'Jack In The Box'],
  },
};

I know that, for example, if I want to access the first object's a value, I can say test.One.a, but how do I programmatically access the value of test.One, test.Two, etc. without hardcoding it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use the bracket notation for accessing properties:

test["One"]["a"];
test["Two"]["b"];

These work with strings, so you can use variables:

const test = {
  One: {
    a: 220,
    b: ['Chipotle', 'Subway', 'Habit Burger'],
  },
  Two: {
    a: 110,
    b: ['Chipotle'],
  },
  Three: {
    a: 200,
    b: ['Subway', 'Jack In The Box'],
  },
  Four: {
    a: 460,
    b: ['Chipotle', 'Subway', 'Habit Burger', 'Jack In The Box'],
  },
};

const first = Object.keys(test)[Math.floor(Math.random() * 4)];
const second = ["a", "b"][Math.floor(Math.random() * 2)];

console.log(first, second, test[first][second])

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda