2017-07-26 106 views
1

你好,我在我的函數返回一個對象的問題,比方說,我有一個對象:JavaScript的按價值計算深嵌套對象/數組找到

var elements = [{ 
    "fields": null, 
    "id_base": "nv_container", 
    "icon": "layout", 
    "name": "container", 
    "is_container": true, 
    "elements" : [ 
     //another elements set here 
    ] 
}, 
{ 
    "id_base": "novo_example_elementsec", 
    "name": "hello", 
    "icon": "edit", 
    "view": {} 
}]; 

我想要的是一個函數(在純JavaScript),可以找到一個特定的鍵和值的對象,我已經創建了一個函數,但它只是不能正常工作? ,我的功能:

function findNested(obj, key, value) { 
    //Early return 
    if (obj[key] === value) { 
     console.log('before return'); //until here . its fine 
     return obj; //not working 
    } else { 
     for (var i = 0, len = Object.keys(obj).length; i <= len; i++) { 
      if (typeof obj[i] == 'object') { 
       this.findNested(obj[i] , key, value); 
      } 
     } 
    } 
} 

我只是不明白我做錯了什麼?

謝謝。

回答

1

您在遞歸調用後錯過了返回。如果在遞歸之後找到該對象,則需要繼續冒泡該結果(通過返回它)。正如@ scott-marcus指出的那樣,您還應該使用i < len(而不是i <= len)。

var elements = [{ 
 
    "fields": null, 
 
    "id_base": "nv_container", 
 
    "icon": "layout", 
 
    "name": "container", 
 
    "is_container": true, 
 
    "elements": [ 
 
     //another elements set here 
 
    ] 
 
    }, 
 
    { 
 
    "id_base": "novo_example_elementsec", 
 
    "name": "hello", 
 
    "icon": "edit", 
 
    "view": {} 
 
    } 
 
]; 
 

 
function findNested(obj, key, value) { 
 
    // Base case 
 
    if (obj[key] === value) { 
 
    return obj; 
 
    } else { 
 
    for (var i = 0, len = Object.keys(obj).length; i < len; i++) { 
 
     if (typeof obj[i] == 'object') { 
 
     var found = this.findNested(obj[i], key, value); 
 
     if (found) { 
 
      // If the object was found in the recursive call, bubble it up. 
 
      return found; 
 
     } 
 
     } 
 
    } 
 
    } 
 
} 
 

 
console.log(findNested(elements, "icon", "layout")); // returns object 
 
console.log(findNested(elements, "icon", "edit")); // returns object 
 
console.log(findNested(elements, "foo", "bar")); // returns undefined

+0

非常感謝@smarx,這就是我想要的,我一直在尋找6小時,由於解決方案再次 –