查找嵌套对象的键并返回其路径 [英] Find key of nested object and return its path
本文介绍了查找嵌套对象的键并返回其路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道一个好的javascript npm包(或具有一些好的功能)来查找JSON密钥并返回其路径(或路径(如果密钥在嵌套JSON中不止一次存在))
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"
我想使用一个函数,该函数将返回此键的路径,在上面的示例中,键"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
console.log(getKeyPath(person,"long");
//address.long , long
推荐答案
使用 obj-flatten
您可以将其制成平面对象:
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"]
这篇关于查找嵌套对象的键并返回其路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文