javascript javascript查找数组项的父项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5153998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:10:59  来源:igfitidea点击:

javascript find parent of array item

javascriptarraysparent

提问by Mark

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
}

回答by Martijn

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

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

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:

为此,您必须引用“根”数组,这取决于您的数据模型。
假设 USA 是可访问的,并且只包含数组,你可以这样做:

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;
                }
            }
        }
    }
}

Note that I've renamed the arrayparameter to itemsince you're passing along a value (and array item), and you expect the array to be returned.
If you want to know the nameof the array, you should return memberinstead.

请注意,我已将array参数重命名为,item因为您正在传递一个值(和数组项),并且您希望返回该数组。
如果你想知道数组的名称,你应该返回member

回答by Frederic Fortier

Here is a generic function that can be used to find the parent key of any kind of multi-dimentional object. I use underscore.js by habit and for conciseness to abstract array vs associative array loops.

这是一个通用函数,可用于查找任何类型的多维对象的父键。我习惯使用 underscore.js 并且为了简洁抽象数组与关联数组循环。

(function (root, struct) {
    var parent = null;
    var check = function (root, struct) {
        _.each(root, function (value, key) {
            if (value == struct) {
                parent = key;
            } else if (root == struct) {
                parent = '_root';
            } else if (typeof value === 'object') {
                check(value, struct);
            }
        });
    }
    check(root, struct);
    return parent;
})