-3

I have a nested JS array, but i'm unsure how to access the values that I need. In this scenario, I have a "active_district" ID. I want to get an array of all of the schools nested under that district. But that the schools are 3 levels down the array so i'm unsure how to reach them.

My array looks like this: enter image description here

How can I get an array of these schools?

Jay
  • 928
  • 2
  • 7
  • 28
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Dylan Watt May 12 '15 at 21:29

1 Answers1

1

Divide and conquer: First, get access to the array of districts:

var districts = yourArray[0][0].active_districts;

From your picture, I can see that we want to access index 0 of the topmost array, and index 0 of that array. (I don't know why, but that's clear from the picture in your question. It's odd to have an array and just always grab the first entry from it.)

Now, find the district you want:

var district;
districts.some(function(d) {
    if (d.id === yourDistrictId) {
        district = d;
        return true; // Stops loop
    }
    return false;
};

Now, provided district is not undefined, the schools are on district.schools.


(That uses Array#some, which was added in ECMAScript5 and is on all modern browsers. It's not on IE8 and some other older browsers, but it can be "polyfilled." So if you need to support older browsers, look for a polyfill. Or use a for loop.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875