Find key of nested object and return its path

筅森魡賤 提交于 2019-12-11 05:10:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!