Find an element in an array recursively

后端 未结 3 1338
情深已故
情深已故 2021-01-04 05:55

I have an array of objects. Every object in the array has an id and an item property that is an array containing other object. I need to be able to find an element in an arr

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 06:36

    You should replace

      getSubMenuItem(subMenuItems[i].items, id);
    

    with

      var found = getSubMenuItem(subMenuItems[i].items, id);
      if (found) return found;
    

    in order to return the element when it is found.

    And be careful with the name of the properties, javascript is case sensitive, so you must also replace

      if (subMenuItems[i].Id == id) {
    

    with

      if (subMenuItems[i].id == id) {
    

    Demonstration


    Final (cleaned) code :

    var getSubMenuItem = function (subMenuItems, id) {
        if (subMenuItems) {
            for (var i = 0; i < subMenuItems.length; i++) {
                if (subMenuItems[i].id == id) {
                    return subMenuItems[i];
                }
                var found = getSubMenuItem(subMenuItems[i].items, id);
                if (found) return found;
            }
        }
    };
    

提交回复
热议问题