-2
const myArrayOfObjects = [
  {id: 1, children: [{id: 2, children: [{id: 3}]}]},
  {id: 4, children: [{id: 5}]},
  {id: 6, children: [{id: 7}]}
]

I have array with a lot of objects which can have many children arrays but every object has unique key. So How I can loop through main array and delete some object? For example object with id 3

Amol.D
  • 117
  • 8
  • Welcome to SO. First, you should start with making sure your data structure is valid and doesn't have typos, missing commas, or missing brackets. – Andy Apr 05 '22 at 09:56
  • https://stackoverflow.com/questions/8085004/iterate-through-nested-javascript-objects – Sarah Apr 05 '22 at 10:11

3 Answers3

0

You can use indexOf() to find the index of the array and use that index with .splice() to remove the element

Pietro Teggi
  • 104
  • 7
0
  1. Your data structure is full of errors. Missing brackets, typos etc, so you need to fix those first. You can use a tool like JSCompress to point out the errors.

  2. Use a recursive function that takes an array of objects, and an id, loops over the array, and checks the id. If the object id is the same as the argument id splice out the object.

  3. Then, if the object has children pass that array back into the function and repeat the process.

  4. Finally return the updated array.

const arr=[{id:1,children:[{id:2,children:[{id:3}]}]},{id:4,children:[{id:5}]},{id:6,children:[{id:7,children:[{id:7}]}]}];

function remove(arr, id) {
  for (let i = 0; i < arr.length; i++) {
    const obj = arr[i];
    if (obj.id === id) arr.splice(i, 1);
    if (obj.children) remove(obj.children, id);
  }
  return arr;
}

console.log(remove(arr, 3));
Andy
  • 61,948
  • 13
  • 68
  • 95
0

Use a recursive function to search for and delete the object in the array. If the children array is empty after the element has been found, delete the children property from the parent object.

const arr = [
  {id: 1, children: [{id: 2, children: [{id: 3}]}]},
  {id: 4, children: [{id: 5}]},
  {id: 6, children: [{id: 7, children: [{id: 7}]}]}
];

function findObjectToDelete(array, idToDelete) {
    for(let i=0;i<array.length;i++) {
        const obj = array[i];
        if(obj.id === idToDelete){
            array.splice(i,1);
            break;
        }
        if(obj.children) {
            findObjectToDelete(obj.children, idToDelete);
            if(obj.children.length===0) {
                delete obj.children;
            }
        }
    }
    return array;
}
const newArr = findObjectToDelete(arr,3);
console.log(newArr);
Sarah
  • 68
  • 1
  • 5