簡體   English   中英

查找項目是否存在於深層嵌套的子數組中?

[英]Find item if exist in deep nested children array?

我需要查找項目是否存在於深層嵌套數組中。

例子:

let arr = [
  {
   id: 1 ,
   title : 'Test' ,
   children: 
  [
    {id: 1 , title: 'Title' , hasChild : true },
    {id: 1 , title: 'Title' , hasChild : false },
    {id: 1 , title: 'Title' },
  ] 
 },
]

我需要循環思考arr.children並嘗試查找它是否具有名稱為hasChild的屬性 find item 並將其設置為 false。

循環后我需要得到一個數組,如

let arr = [
  {
   id: 1 ,
   title : 'Test' ,
   children: 
  [
    {id: 1 , title: 'Title' , hasChild : false }, //here is changed hasChild to false
    {id: 1 , title: 'Title' , hasChild : false },
    {id: 1 , title: 'Title' },
  ] 
 },
]

我找到了方法,但我需要更好的解決方案:

    arr.map(it) => {
      if (it.hasChild) {
        it.dashCheck = false; 
      }
    });

您可以使用遞歸函數對無限嵌套的對象/數組等進行操作。

function recursiveUpdate(array, index) {
  const element = array[index];
  if(!element) return;
  if(Object.keys(element).indexOf('children') > -1) {
    element.hasChild = true;
    recursiveUpdate(element['children'], 0);
  } else {
    element.hasChild = false;
    recursiveUpdate(array, index+1);
  }
}

recursiveUpdate(arr, 0);

如果arr的結構總是像您在問題中提到的那樣,您可以使用Array class 的forEach方法簡單地遍歷children

arr.forEach(item => {
  item.children.forEach(child => {
    child.hasChild = child.hasChild === true ? false : child.hasChild;
  });
});

注意:這將更改原始數組,並且不會使用更改后的hasChild值創建副本。

演示:

 let arr = [{ id: 1, title: 'Test', children: [ {id: 1, title: 'Title', hasChild: true }, {id: 1, title: 'Title', hasChild: false }, {id: 1, title: 'Title' }, ] }]; arr.forEach((obj) => { obj.children.forEach((childObj) => { if (childObj.hasChild) { childObj.hasChild = false; } }); }); console.log(arr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM