Search Within Multilevel Json Tree Using Multiple Keys
I have a json tree with following structure { 'treeId': 'avhsgdkendkfhjsdoiendsj', 'groupResponse': { 'description': null, 'id': 'avhsgdkendkfhjsdoiendsj',
Solution 1:
The following might help,
vardata = {
'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'
}
}
]
};
var search = function(data, qObj){
var i, k, matched = true, set = [];
for (k in qObj) {
if(!qObj.hasOwnProperty(k))
continue;
if(!data.groupResponse.hasOwnProperty(k) || data.groupResponse[k] != qObj[k]){
matched = false;
break;
}
}
if(matched){
set.push(data.groupResponse);
}
for(i = 0; i < data.childResponse.length; i++){
s = search(data.childResponse[i], qObj);
Array.prototype.push.apply(set, s);
}
returnset;
}
console.log(search(data, { "mAttr": "xxx", "mAttrVal": "222"}));
Output:
[{"description":null,"id ":"6p263uh38xvnchmsrw2jn48ut","mAttr":"xxx","mAttrVal":"222"}]
hope this helps
Solution 2:
I didn't test it, but I think it should work
Object.prototype.findKey = function(keyObj) {
var p,key,tRet=[],add=true;
for (p inthis) {
if (this[p] instanceof Object) {
if (this.hasOwnProperty(p)) {
tRet.concat(this[p].findKey(keyObj));
}
}
}
for(key in keyObj){
if(!this.hasOwnProperty(key)||!this[key]===keyObj[key])
add=false;
}
if(add)
tRet.push(this);
return tRet;
};
Tell me if I'm wrong ;)
Post a Comment for "Search Within Multilevel Json Tree Using Multiple Keys"