访问嵌套JavaScript数组 [英] Accessing a nested javascript array

查看:118
本文介绍了访问嵌套JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的JS数组,但我不能确定如何获得我需要的值。在这种情况下,我有一个active_districtID。我想获得的所有区下嵌套在学校的数组。但该学校是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:

我怎样才能得到这些学校的数组?

How can I get an array of these schools?

推荐答案

分而治之:首先,获得进入各区的数组:

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

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

从你的照片,我可以看到,我们要访问指数 0 最上面的阵列,而指数 0 是数组。 (我不知道的为什么,但这是从你的问题画面清晰。这是奇怪,有一个数组,只是总是抢在它的第一项。)

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.)

现在,找到你要的区:

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

现在,只要不是未定义,学校都在 district.schools

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

(使用阵列#有些,这是在ECMAScript5添加,并且是所有现代浏览器,它是不是在IE8和其他一些老的浏览器,但它可polyfilled。所以,如果你需要支持旧的浏览器,寻找一个填充工具,或者使用循环。)

(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.)

这篇关于访问嵌套JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆