【发布时间】:2015-04-20 08:24:04
【问题描述】:
我有一个具有以下结构的 json 树
{
"treeId": "avhsgdkendkfhjsdoiendsj",
"groupResponse": {
"description": null,
"id": "avhsgdkendkfhjsdoiendsj",
"mAttr": null,
"mAttrVal": null
},
"childResponse": [
{
"treeId": "6p263uh38xvnchmsrw2jn48ut",
"childResponse": [],
"groupResponse": {
"description":null,
"id ":"6p263uh38xvnchmsrw2jn48ut",
"mAttr": "xxx",
"mAttrVal": "222"
}
},
{
"treeId": "2fywxwi93lg7fqggdqqpqxvpg",
"childResponse": [],
"groupResponse": {
"description ":null,
"id": "2fywxwi93lg7fqggdqqpqxvpg",
"mAttr": "xxx",
"mAttrVal": "111"
}
}
]
}
我想基于单个/多个键搜索节点,例如{ "mAttr": "xxx", "mAttrVal","222"}
我找到了this answer中提到的解决方案
Object.prototype.findKey = function(keyObj) {
var p, key, val, tRet;
for (p in keyObj) {
if (keyObj.hasOwnProperty(p)) {
key = p;
val = keyObj[p];
}
}
for (p in this) {
if (p == key) {
if (this[p] == val) {
return this;
}
} else if (this[p] instanceof Object) {
if (this.hasOwnProperty(p)) {
tRet = this[p].findKey(keyObj);
if (tRet) { return tRet; }
}
}
}
return false;
};
它可以基于任何单个键进行搜索。如何修改它以使用多个键?我的树的深度没有限制。
【问题讨论】:
-
你只想要第一个对象或每个对象都有这些键/值吗?
-
@JuniusRendel 我想要所有这样的节点
标签: javascript jquery json tree