javascript - 递归查找 JSON 值

标签 javascript json

我在 chrome 中遇到异常:“RangeError:超出最大调用堆栈大小”

我正在尝试提取名为“menus”的 JSON 值,其中包含子菜单

查看我的jsfiddle link

==JAVASCRIPT==

gedControllers.factory('getmenu', function($timeout, $http) {
    var menu = {
        fetch: function() {
            return $timeout(function() {
                return $http.get('config.json').then(function(response) {
                    return response.data;
                });
            }, 3);
        }
    }

    return menu;
});

function isInArray(needle, haystack) {
    var foundNeedle = false;

    for (var key in haystack) {

        if (isInArray(needle, haystack[key])) {
            foundNeedle = true;
        }

        if (key == needle) {
            foundNeedle = true
        }
    }

    return foundNeedle;
}

gedControllers.controller('AppCtrl', function($scope, getmenu) {
    getmenu.fetch().then(function(data) {
        $scope.data = data;
        $scope.menu = isInArray("menu",data);
        console.log($scope.menu);
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

   
    <div ng-controller='AppCtrl'>
            <script type="text/ng-template" id="categoryTree">
                {{ category.label }}
                <ul ng-if="category.menus">
                    <li ng-repeat="category in category.menus" ng-include="'categoryTree'">
                    </li>
                </ul>
            </script>
            <ul>
                <li ng-repeat="category in menus" ng-include="'categoryTree'"></li>
            </ul>
        </div>

但是原始的 json 我要大[plunker link][2]

[2]:http://plnkr.co/edit/GSwlCl0y2j6HRABf98pd?p=preview “plunker 链接哪个错误”

如何优化我的代码?

最佳答案

这些只是 Javascript 对象。您正在寻求进行深度搜索。您可以采用以下方法:

function deepKeySearch(obj, key) {
  for (iKey in obj) {
    if (obj.hasOwnProperty(iKey)) {
      if (iKey === key) {
        return obj[iKey];
      } else if (typeof obj[iKey] === 'object' && obj[iKey] !== null) {
        var search = deepKeySearch(obj[iKey], key);
        if (search !== undefined) {
          return search;
        }
      }
    }
  }
}

var obj = {
  obj: {
    obj: {
      menu: 'Hey',
      arrTest: [0]
    }
  }
}

console.log(deepKeySearch(obj, 'menu') !== undefined); //does exist
console.log(deepKeySearch(obj, 'nonExistantKey') !== undefined); //doesn't exist
console.log(deepKeySearch(obj, 'arrTest') !== undefined); //does exist

如果您只想检查 key 是否存在,可以重写:

function deepKeySearch(obj, key) {
    var keys = Object.keys(obj);
    return keys.some(function (iKey) {
        if (iKey === key) {
            return true;
        } else if (typeof obj[iKey] === 'object' && obj[iKey] !== null) {
            return deepKeySearch(obj[iKey], key);
        }
    });
}

var obj = {
    obj: {
        obj: {
            menu: 'Hey',
            arrTest: [0]
        }
    }
}

console.log(deepKeySearch(obj, 'menu')); //does exist
console.log(deepKeySearch(obj, 'nonExistantKey')); //doesn't exist
console.log(deepKeySearch(obj, '0')); //does exist

关于javascript - 递归查找 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875384/

相关文章:

json - 如何在 Kotlin 中从字符串创建 JSONObject?

c# - 使用 FromBody 在 WebAPI 中建模的对象的 JSON 数组

javascript - 如果我们得到某个结果,请重试函数 promise

javascript - 为什么这段代码添加空的 img 标签?

javascript - 如何在 javascript 中使用前瞻来实现负面回顾?

javascript - Google Maps API v3 - 带动画的多点

javascript - Meteor 在运行时更改数据库

javascript - 如何使用 JS 每小时运行一次代码?

json - 如何将 emacs 连接到 json 服务?

php - 转换编码的 utf-8 JSON