javascript find by value deep in a nested object/array

前端 未结 1 825
北恋
北恋 2021-01-05 00:35

hello , I have a problem returning an object in my function, Let\'s say I have an object:

var elements = [{
    \"fields\": null,
    \"id_b         


        
相关标签:
1条回答
  • 2021-01-05 01:18

    You're missing a return after making the recursive call. If the object is found after recursing, you need to continue to bubble that result up (by returning it). You should also be using i < len (not i <= len) as pointed out by @scott-marcus.

    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 讨论(0)
提交回复
热议问题