javascript find parent of array item

守給你的承諾、 提交于 2019-12-24 05:19:07

问题


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
}

回答1:


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

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

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.




回答2:


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.

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


来源:https://stackoverflow.com/questions/5153998/javascript-find-parent-of-array-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!