javascript查找数组项的父级 [英] javascript find parent of array item

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

问题描述

我有一个像这样的数组项:

I have an array item like this:

var array = USA.NY[2];
// gives "Albany"

{"USA" : {
  "NY" : ["New York City", "Long Island", "Albany"]
}}

我只想从数组中查找状态.我该怎么做呢?谢谢.

I want to find the state from just having the array. How do I do this? Thanks.

function findParent(array) {
  // do something
  // return NY
}

推荐答案

在Javascript中,数组元素没有引用包含它们的数组.

In Javascript, array elements have no reference to the array(s) containing them.

要实现此目的,您将需要引用"root"数组,这取决于您的数据模型.
假设USA是可访问的,并且仅包含数组,则可以执行以下操作:

To achieve this, you will have to have a reference to the 'root' array, which will depend on your data model.
Assuming USA is accessible, and contains only arrays, you could do this:

function findParent(item) {
    var member, i, array;
    for (member in USA) {
        if (USA.hasOwnProperty(member) && typeof USA[member] === 'object' && USA[member] instanceof Array) {
            array = USA[member];
            for(i = 0; i < array.length; i += 1) {
                if (array[i] === item) {
                    return array;
                }
            }
        }
    }
}

请注意,由于您传递的是值(和数组项),因此我已将 array 参数重命名为 item ,并且希望返回数组.
如果您想知道数组的名称,则应该返回 member .

Note that I’ve renamed the array parameter to item since you’re passing along a value (and array item), and you expect the array to be returned.
If you want to know the name of the array, you should return member instead.

这篇关于javascript查找数组项的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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