Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

71
Views
How to locate and delete an item into array of objects

I have an array as:

const arr=[{
        id: 9,
        name: 'Patrimônios',
        children: [],
      },
      {
        id: 10,
        name: 'Despesas',
        children: [
          { id: 16, name: 'Manutenção' },
          { id: 17, name: 'Despesa' },
          { id: 18, name: 'Impostos' },
          { id: 19, name: 'Gráfica' },
        ],
      },
....]

I´d like a function to delete a item by id. As we can see the item can be into 'children' or not. If the item is in the "children" I´d like to delete it from children array only.

I´d like something as:

findById(tree, nodeId) {
  for (const node of tree) {
    if (node.id === nodeId) return node

    if (node.children && node.children.length) {
      const desiredNode = this.findById(node.children, nodeId)
      if (desiredNode) return desiredNode
    }
  }
  return false
},
function deleteItemById(arr,id){
  item=findById(arr,id)
  if (item){
    ///   here How I can delete it?
  }
}

How could I do that?

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

Here is a recursive function that matches your code's terminology to filter an object by id:

const removeObjectByIdRecursively = (list, id) => list.reduce((acc, item) => {
  if (item.id === id) return acc;
  if (item.children) {
    return [
      ...acc,
      {
        ...item,
        children: removeObjectByIdRecursively(item.children, id)
      }
    ];
  }
  return [
    ...acc,
    item
  ];
}, []);
7 months ago · Juan Pablo Isaza Report

0

Super basic, untested and targeted directly at the shape of your data, but this shows how you can use Array.filter() to return a new array that doesn't contain the elements you want to remove by id.

const testArray = [
  { id: 0, value: "zero" },
  { id: 1, value: "one", children: [{ id: 3 }] },
  { id: 2, value: "two" },
  { id: 3, value: "three" },
  { id: 4, value: "four" },
];

const deleteObjectById = ({ ary, id }) => ary.filter((item) => {
  const child = (item.children || []).find((c) => c.id === id);

  return item.id !== id && !(!!child);
});

const filteredArray = deleteObjectById({
  ary: testArray,
  id: 3,
});

console.log(testArray);
console.log(filteredArray);
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs