0

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.

Santiago Esquivel
  • 380
  • 1
  • 5
  • 15

2 Answers2

1

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/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • This worked perfectly for me thank you, all I have to do is some further implementation with my UI, but this gets the desired output. Thanks again. – Santiago Esquivel Mar 02 '15 at 15:20
0

Recursion is the way to go. See @T.J. Crowder's answer Loop through nested objects with jQuery

Community
  • 1
  • 1
Simo Mafuxwana
  • 3,702
  • 6
  • 41
  • 59