Search code examples
javascriptdictionaryfilternested-object

map nested array in javascript


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

Solution

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