Search code examples
javascriptarraysjsonobjectrecursion

How do I remove object (element) in Javascript object?


How do I remove an element from a JavaScript object by ID? For instance I have to remove 004 or 007:

const obj = {
  id: '001',
  children: [
    {
      id: '002',
      children: [
        {
          id: '003',
          children: [],
        },
        {
          id: '004',
          children: [
            {
              id: '005',
              children: [],
            }
          ],
        }
      ],
    },
    {
      id: '006',
      children: [
        {
          id: '007',
          children: [],
        }
      ],
    },
  ]
}

i am trying to like this, find id but what should be next. It is expected to remove id from the object.

const removeById = (obj = {}, id = '') => {
  console.log('obj: ', obj)

  const search = obj.children.find(o => o.id === id)
  console.log('##search: ', search)
  if(search) {
    console.log('## parent id: ', obj.id)
    ...
  }
  if (obj.children && obj.children.length > 0) {
    obj.children.forEach(el => removeById(el, id));
  }
}

removeById(obj, '007')

Solution

  • You can use findIndex to get the location in the array. To remove an element from an array you need to use splice.

    You can then loop over the children with some and check the children's children. Using some, you can exit out when you find the id so you do not have to keep looping.

    let obj = {
      id: '001',
      children: [
        {
          id: '002',
          children: [
            {
              id: '003',
              children: [],
            },
            {
              id: '004',
              children: [
                {
                  id: '005',
                  children: [],
                }
              ],
            }
          ],
        },
        {
          id: '006',
          children: [
            {
              id: '007',
              children: [],
            }
          ],
        },
      ]
    }
    
    const removeById = (parentData, removeId) => {
    
       // This is only the parent level!
       // If you will never delete the first level parent, this is not needed
       if (parentData.id === removeId){
         Object.keys(data).forEach(key => delete parentData[key]);
         return true;
       }
       
       function recursiveFind (children) {
         // check if any of the children have the id
         const index = children.findIndex(({id}) => id === removeId);
     
         // if we have an index
         if (index != -1) {
           // remove it
           children.splice(index, 1);
           // say we found it
           return true;
         }
       
         // Loop over the chldren check their children
         return children.some(child => recursiveFind(child.children));
       }
    
       return recursiveFind(parentData.children);
    }
    
    
    removeById(obj,'004');
    removeById(obj,'007');
    console.log(obj)