Javascript find parent of array element

I have an array element similar to this:

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

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

      

I only want to find the state from an array. How should I do it? Thank.

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

      

+1


source to share


2 answers


In Javascript, array elements do not have a reference to the containing array (s).

To achieve this, you will need to have a reference to the "root" array, which will depend on your data model.
Assuming US is available and only contains arrays, you can 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 parameter array

to item

as you are looping along the value (and array element) and you are expecting an array to return.
If you want to know the name of the array, you must return member

.

+5


source


Here is a general function that can be used to find the parent key of any type of multidimensional object. I use underscore.js out of habit and for brevity abstract array versus array associative 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;

      



})

+1


source







All Articles