Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!