[英]iterate through object and filter given a specific value in a given property javascript
我在網上看過,無法找到關於我所遇到問題的詳細答案。 我有一個看起來像這樣的對象:
{
"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中知道在obj中有一個for var,但是我不確定如何實現它以便獲取所需的輸出。 任何幫助或指導將不勝感激。
如果您知道這僅是一個級別的深度(“ 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");
遞歸是必經之路。 參見@TJ Crowder的答案使用jQuery遍歷嵌套對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.