Skip to content Skip to sidebar Skip to footer

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 exampl

Solution 1:

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"]

Solution 2:

Native javascript is always recommended if you are learning the language but you can use the lodash library. https://lodash.com/docs/4.17.4#at

Read some methods like _.at(), _.has(), or _.findKey()

Post a Comment for "Find Key Of Nested Object And Return Its Path"