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

125
Visualizações
Use string "array[n]" as variable

I dont know how to really explain this, but here my problem.

i have a string "myKey[2]" and i want to

const values = {
 "myKey": ["hey", "oh"],
 "b": ["something"]
};

const str = "myKey[2]";

My question is : how to get "oh" with a string as a variable name + is there something in js who can read "myarray.key" as variable too without apply many regex and function ?

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

0

As the indexing for the array starts from zero, accessing "myKey[2]" will give you undefined.Assuming you want to take the second element from the array,we can do

const values = {
 "myKey": ["hey", "oh"],
 "b": ["something"]
};

const str = "myKey[1]";

const result=values[str.slice(0, str.indexOf('['))][
  Number(str.slice(str.indexOf('[') + 1, str.indexOf(']')))
];

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Your string should be

const str = values.myKey[1];

or if your key has dashes and such

const str = values['myKey'][1];

Keep in mind that the right index in this case is 1, not 2 as the index numbering in arrays starts from 0 and not 1.

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