2

I have a nested array of objects like this:

let data = [
  {
      id: 1,
      title: "Abc",
      children: [
          {
              id: 2,
              title: "Type 2",
              children: [
                  {
                      id: 23,
                      title: "Number 3",
                      children:[] /* This key needs to be deleted */
                  }
              ]
          },
      ]
  },
  {
      id: 167,
      title: "Cde",
      children:[] /* This key needs to be deleted */
  }
] 

All I want is to recursively find leaves with no children (currently an empty array) and remove the children property from them.

Here's my code:

normalizeData(data, arr = []) {
    return data.map((x) => {
        if (Array.isArray(x))
            return this.normalizeData(x, arr)
        return {
            ...x,
            title: x.name,
            children: x.children.length ? [...x.children] : null
        }
    })
}
Ivan
  • 34,531
  • 8
  • 55
  • 100
Amir Shahbabaie
  • 1,352
  • 2
  • 14
  • 33

4 Answers4

4

You need to use recursion for that:

let data = [{
    id: 1,
    title: "Abc",
    children: [{
      id: 2,
      title: "Type 2",
      children: [{
        id: 23,
        title: "Number 3",
        children: [] /* This key needs to be deleted */
      }]
    }]
  },
  {
    id: 167,
    title: "Cde",
    children: [] /* This key needs to be deleted */
  }
]

function traverse(obj) {
  for (const k in obj) {
    if (typeof obj[k] == 'object' && obj[k] !== null) {
      if (k === 'children' && !obj[k].length) {
        delete obj[k]
      } else {
        traverse(obj[k])              
      }
    }
  }
}

traverse(data)
console.log(data)
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
3

Nik's answer is fine (though I don't see the point of accessing the children key like that), but here's a shorter alternative if it can help:

let data = [
  {id: 1, title: "Abc", children: [
    {id: 2, title: "Type 2", children: [
      {id: 23, title: "Number 3", children: []}
    ]}
  ]},
  {id: 167, title: "Cde", children: []}
];

data.forEach(deleteEmptyChildren = o => 
  o.children.length ? o.children.forEach(deleteEmptyChildren) : delete o.children);

console.log(data);

If children is not always there, you can change the main part of the code to:

data.forEach(deleteEmptyChildren = o => 
  o.children && o.children.length 
    ? o.children.forEach(deleteEmptyChildren) 
    : delete o.children);
Jeto
  • 14,596
  • 2
  • 32
  • 46
  • That's a very nice solution – Ivan Jan 26 '19 at 14:23
  • This will fail if there is no children key in object – Code Maniac Jan 26 '19 at 14:48
  • 1
    I am just not a fan of the extra loop to initialize it. – epascarello Jan 26 '19 at 14:51
  • 1
    @CodeManiac Well looking at OP's input, it seems like it's always here even when it's empty (that's why he wants to remove them to begin with). Code's easily adjustable though if that's not the case. – Jeto Jan 26 '19 at 14:52
  • 1
    @CodeManiac `e.children && e.children.length` solves the issue so not a big deal – epascarello Jan 26 '19 at 14:53
  • @epascarello I kinda like it more when the function applies to actual items, as opposed to a collection of items, especially if it's supposed to be reused in differenct circumstances. Matter of preference I suppose. – Jeto Jan 26 '19 at 14:54
2

You can do it like this using recursion.

So here the basic idea is in removeEmptyChild function we check if the children length is non zero or not. so if it is we loop through each element in children array and pass them function again as parameter, if the children length is zero we delete the children key.

let data=[{id:1,title:"Abc",children:[{id:2,title:"Type2",children:[{id:23,title:"Number3",children:[]}]},]},{id:167,title:"Cde",children:[]},{id:1}]

function removeEmptyChild(input){
  if( input.children && input.children.length ){
    input.children.forEach(e => removeEmptyChild(e) )
  } else {
    delete input.children
  }
  return input
}

data.forEach(e=> removeEmptyChild(e))

console.log(data)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
2

Simple recursion with forEach is all that is needed.

let data = [{
    id: 1,
    title: "Abc",
    children: [{
      id: 2,
      title: "Type 2",
      children: [{
        id: 23,
        title: "Number 3",
        children: [] /* This key needs to be deleted */
      }]
    }, ]
  },
  {
    id: 167,
    title: "Cde",
    children: [] /* This key needs to be deleted */
  }
]

const cleanUp = data =>
  data.forEach(n =>
    n.children.length
      ? cleanUp(n.children)
      : (delete n.children))
      
      
cleanUp(data)
console.log(data)

This assumes children is there. If it could be missing than just needs a minor change to the check so it does not error out on the length check. n.children && n.children.length

epascarello
  • 204,599
  • 20
  • 195
  • 236