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
        }
    })
}
2
  • 1
    Your efforts till now ? Commented Jan 26, 2019 at 14:10
  • 1
    added code, please take a look Commented Jan 26, 2019 at 14:13

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

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);

6 Comments

That's a very nice solution
This will fail if there is no children key in object
I am just not a fan of the extra loop to initialize it.
@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.
@CodeManiac e.children && e.children.length solves the issue so not a big deal
|
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

Comments

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)

2 Comments

why are you using map?
@epascarello oh my bad. i overlooked use of map here. thanks for pointing out best case to use forEach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.