Reputation: 380
I have looked online and have been unable to find a detailed answer on the question I am having. I have an object which looks something like this:
{
"00001": {
"sid": "00001",
"oid": "00001",
"name": "operation 0001 service 1",
"description": "test operation 000001",
"returntype": "something",
"parameters": {
"00001": {
"pid": "00001",
"name": "parameter 00001 operation 0001 service 1",
"description": "test parameter 000001",
"type": "something"
}
}
},
"00002": {
"sid": "00002",
"oid": "00002",
"name": "operation 0001 service 2",
"description": "test operation 000001",
"returntype": "something",
"parameters": {}
},
"00003": {
"sid": "00003",
"oid": "00003",
"name": "operation 0001 service 3",
"description": "test operation 000001",
"returntype": "something",
"parameters": {}
},
"00004": {
"sid": "00004",
"oid": "00004",
"name": "operation 0001 service 4",
"description": "test operation 000001",
"returntype": "something",
"parameters": {}
},
"00005": {
"sid": "00005",
"oid": "00005",
"name": "operation 0001 service 5",
"description": "test operation 000001",
"returntype": "something",
"parameters": {}
},
"00006": {
"sid": "00001",
"oid": "00006",
"name": "operation 0001 service 6",
"description": "test operation 000001",
"returntype": "something",
"parameters": {}
}
}
I am trying to iterate through the objects and be able to return the ones that have a specific sid (i.e. 00001) I know in javascript there is a for var in obj, but I am unsure on how to implement it in order to get the desired output. Any help or guidance will be appreciated.
Upvotes: 0
Views: 50
Reputation: 707328
If you know this is one level deep only ("sid" matches will only be found at the first level of objects and you aren't searching nested objects too), then it is more straightfoward:
function findMatches(data, prop, val) {
var item, matches = [];
for (var obj in data) {
item = data[obj];
if (item[prop] === val) {
matches.push(item);
}
}
return matches;
}
var result = findMatches(myData, "sid", "00001");
Working demo: http://jsfiddle.net/jfriend00/s5xg1khy/
Upvotes: 1
Reputation: 3762
Recursion is the way to go. See @T.J. Crowder's answer Loop through nested objects with jQuery
Upvotes: 0