Search code examples
javascriptjsonobjectpath-finding

Find key of nested object and return its path


Does anyone know a good javascript npm package (or have some good function) to find a JSON key and return its path (or paths if key exists more than once in nested JSON)

for example:
var person={
"name":myName,
"address":{
"city",
"location":{
"long":123,
"lat":456
}
"long"

I want to use a function that will return the path to this key, in above example the key "long" exist twice:

console.log(getKeyPath(person,"long"); //address.long , long


Solution

  • Using obj-flatten you can make that a flat object:

    var person = {
      "name": "your name"
      "location.long": 123,
      "location.lat": 456,
      "long": 42,
      ...
    }
    

    And then you simply have to query by that pattern:

    var searchKey = "long";
    var yourKeys = Object.keys(person).filter(function (c) {
       return c.split(".").indexOf(searchKey) !== -1;
    });
    // => ["location.long", "long"]