我有一個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"
}
}
]
}
我想基於單個/多個密鑰(S)來搜索節點例如{ "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;
};
它可以搜索基於任何一個鍵。如何修改它以使用多個鍵?我的樹的深度沒有限制。
你只需要第一個對象或每個對象與這些鍵/值? – n00dl3
@JuniusRendel我想要所有這樣的節點 – anu