Skip to content
Advertisement

Find empty arrays in nested array and remove them in Javascript

I have a nested and hierarchical array of objects, which looks like this

[{
"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": []
    },
    ...

Now I want to remove the empty array "children": [] from the last children.

I’ve tried it with reduce but it doesn’t work without any error.

   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)

Advertisement

Answer

You could use recursion for that.

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));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement