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
}
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:
Note that I’ve renamed the
array
parameter toitem
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.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.