larry ckey
larry ckey

Reputation: 141

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

Upvotes: 1

Views: 2521

Answers (2)

Chris
Chris

Reputation: 993

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

Upvotes: -1

Ionică Bizău
Ionică Bizău

Reputation: 113335

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

Upvotes: 2

Related Questions