Home > Blockchain >  How do I remove object (element) in Javascript object?
How do I remove object (element) in Javascript object?

Time:11-18

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

CodePudding user response:

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)

CodePudding user response:

We can use a recursive function to do it

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 = (data,id) =>{
  if(data.id === id){
    delete data.id
    delete data.children
    return
   }
   data.children.forEach(d =>{
     removeById(d,id)
   })
}

removeById(obj,'006')
console.log(obj)


Update: not leave an empty object after removing

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

let match = false
const removeById = (data,id) =>{
  match = data.some(d => d.id == id)
  if(match){
      data = data.filter(d => d.id !== id)
   }else{
     data.forEach(d =>{
       d.children = removeById(d.children,id)
     })
   }
   return data
}

let data = [obj]
console.log(removeById(data,'004'))

  • Related