【问题标题】:iterate through object and filter given a specific value in a given property javascript遍历对象并过滤给定属性中给定的特定值javascript
【发布时间】:2015-03-02 14:48:11
【问题描述】:

我在网上查看过,但无法找到有关我所遇到问题的详细答案。我有一个看起来像这样的对象:

 {
"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": {}
}
}

我正在尝试遍历对象并能够返回具有特定 sid(即 00001)的对象 我知道在 javascript 中有一个 for var in obj,但我不确定如何按顺序实现它获得所需的输出。任何帮助或指导将不胜感激。

【问题讨论】:

标签: javascript loops object properties


【解决方案1】:

如果您知道这只是一层深度(“sid”匹配只会在对象的第一层找到,而且您也没有搜索嵌套对象),那么它就更简单了:

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");

工作演示:http://jsfiddle.net/jfriend00/s5xg1khy/

【讨论】:

  • 这对我来说非常有效,谢谢,我所要做的就是对我的 UI 进行一些进一步的实现,但这可以获得所需的输出。再次感谢。
【解决方案2】:

递归是要走的路。见@T.J。克劳德的回答 Loop through nested objects with jQuery

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2021-07-16
    • 1970-01-01
    • 2011-12-10
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多