亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在嵌套數組中查找空數組并在 Javascript 中刪除它們

在嵌套數組中查找空數組并在 Javascript 中刪除它們

守著星空守著你 2023-01-06 16:37:15
我有一個嵌套的分層對象數組,看起來像這樣[{"id": 0,"name": "E00-E90 Stoffwechselst?rungen","parentId": null,"children": [{    "id": 1,    "name": "E70-E90 Stoffwechselst?rungen",    "parentId": 0,    "children": [{        "id": 2,        "name": "E70.- St?rungen des Stoffwechsels aromatischer Aminos?uren",        "parentId": 1,        "children": []    }, {        "id": 3,        "name": "E71.- St?rungen des Stoffwechsels verzweigter Aminos?uren und des Fetts?urestoffwechsels",        "parentId": 1,        "children": []    }, {        "id": 4,        "name": "E72.- Sonstige St?rungen des Aminos?urestoffwechsels",        "parentId": 1,        "children": []    },    ...現在我想"children": []從最后一個孩子中刪除空數組。我試過了,reduce但沒有任何錯誤就無法工作。   var lastElementLength = list.length - 1   const findItemNested = (arr, itemId, nestingKey) => (        arr.reduce((a, item) => {          if (a) return a;          if (item.id === itemId) return item;          if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)        }, null)    );    const resEmptyChildren = findItemNested(roots, lastElementLength, "children");        console.log('resEmptyChildren', resEmptyChildren)
查看完整描述

1 回答

?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

您可以為此使用遞歸。


var tInput = [{

"id": 0,

"name": "E00-E90 Stoffwechselst?rungen",

"parentId": null,

"children": [{

    "id": 1,

    "name": "E70-E90 Stoffwechselst?rungen",

    "parentId": 0,

    "children": [{

        "id": 2,

        "name": "E70.- St?rungen des Stoffwechsels aromatischer Aminos?uren",

        "parentId": 1,

        "children": []

    }, {

        "id": 3,

        "name": "E71.- St?rungen des Stoffwechsels verzweigter Aminos?uren und des Fetts?urestoffwechsels",

        "parentId": 1,

        "children": []

    }, {

        "id": 4,

        "name": "E72.- Sonstige St?rungen des Aminos?urestoffwechsels",

        "parentId": 1,

        "children": []

    }]

  }]

}];


(function removeEmptyChildrenProperties(input){

    console.log('Checking id:', input.id);

    if(input.hasOwnProperty('children')){

        if(input.children && input.children.length){

                input.children.forEach(removeEmptyChildrenProperties)

        }

        else{

            console.log('Remove children on id:', input.id);

            delete input.children

        }

    };

    

    return input

}).apply(null, tInput);


console.log(JSON.stringify(tInput));


查看完整回答
反對 回復 2023-01-06
  • 1 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號