javascript – 如果满足条件,如何获取嵌套数组的ids?

前端之家收集整理的这篇文章主要介绍了javascript – 如果满足条件,如何获取嵌套数组的ids?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个嵌套的数组,一旦满足条件,它应该给所有的父代码,例如我有一个数据数组,我应该在其中匹配

> getParentIds(data,182,[]);

>结果:[96,182];

> getParentIds(data,174,[]);

>结果:[109,219,76,174];

var data = [{
  "id": 96,"name": "test1","items": [{
    "id": 181,"name": "Yes","items": []
  },{
    "id": 182,"name": "No","items": []
  }]
},{
  "id": 109,"name": "Test5","items": [{
    "id": 219,"name": "opt2","items": [{
      "id": 76,"name": "test3","items": [{
        "id": 173,"items": []
      },{
        "id": 174,"items": [{
          "id": 100,"name": "test2","items": [{
            "id": 189,"items": []
          }]
        }]
      }]
    }]
  },{
    "id": 224,"name": "opt3","items": []
  }]
}];


function getParentIds(data,id,parentIds) {
  if (!parentIds) {
    parentIds = [];
  }
  data.map(function(item) {
    if (item.id === id) {
      parentIds.push(item.id);
      return parentIds;
    } else if (item.items.length === 0) {
      // do nothing
    } else {
      return getParentIds(item.items,parentIds);
    }
  });
}

console.log("Array list: " + getParentIds(data,[]));

你能给我任何建议吗?

解决方法

这是一个很酷的问题.我花了比我预期的更多,但这是一个 breadth-first search的实现:
var data = [{
  "id": 96,"items": []
  }]
}];


function parentsOf( arr,parents){
    if (parents.length)
        return parents;
    // I use for(;;) instead of map() because I need the return to exit the loop
    for (var i = 0; i < arr.length; i++){
        if ( arr[i].id == id){
             //push the current element at the front of the parents array
             parents.unshift( arr[i].id );
             return parents;
        };
        if ( arr[i].items ){
            parents = parentsOf(arr[i].items,parents);
            // if the parents array has any elements in it it means we found the child
            if (parents.length){
                parents.unshift(arr[i].id);
                return parents;
            }
        }
    }
    return parents;
}

console.log("Array list for 182: " + parentsOf(data,[]));
console.log("Array list for 174: " + parentsOf(data,[]));
原文链接:https://www.f2er.com/js/152635.html

猜你在找的JavaScript相关文章