问题
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
回答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"]
回答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()
来源:https://stackoverflow.com/questions/44267696/find-key-of-nested-object-and-return-its-path