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

246
Visualizações
Javascript - Error when accessing an associative array value

I have an array, locations:

{
   "locations":[
      "{\"location_id\":\"1\",\"location_name\":\"Main Office\"}",
      "{\"location_id\":\"6\",\"location_name\":\"Secondary\"}"
   ]
}

I am trying to loop through this array to display the location id/name, but keep getting undefined errors.

for (var i = 0; i < locations.length; ++i) {
    alert(locations[i].location_id);
}

If I do alert(locations[i]), I can see the individual array contents for that index, but seemingly have no way go any further.

I feel like I'm missing something incredibly simple and would appreciate any help. Everything I've read suggests I should just be able to get the value of the array by using the for [i] loop.

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

0

I will list all the noticeable problems in your query

  1. "locations" array seems to be a part of another object
  2. All elements of "locations" array are of type String hence the locations[i].location_id would not work as the "dot" operator expects an object

Suggestions

  1. Make sure "locations" is an array of objects which is properly formatted for eg:
let locations = [
    { location_id: 1, location_name: 'Main office'},
    { location_id: 2, location_name: 'any name' },
];
about 4 years ago · Juan Pablo Isaza Relatório

0

define it like:

let locations = [
    { location_id: 1, location_name: 'Main office'},
    { location_id: 2, location_name: 'any name' },
];

locations.forEach(location => {
    alert(location.location_id);
});

Or if your data is in json format:

let json = '{ "locations": [ { "location_id": 3, "location_name": "Name" } ]}';

const data = JSON.parse(json);

data.locations.forEach(location => {
    console.log(location.location_id);
});
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