Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter nested tree object without losing structure

I have nested tree object I would like filter through without losing structure

var items = [
    {
        name: "a1",
        id: 1,
        children: [{
            name: "a2",
            id: 2,
            children: [{
                name: "a3",
                id: 3
            }]
        }]
    }
];

so for example if id == 2 remove object with id 2 and his children

if id == 3 only remove object with id 3

this's just apiece of object to make question clean but the object it self contains more and more :)

using vanilla javascript, _lodash or Angular2 it's okay

thank you

like image 467
Omar Makled Avatar asked Dec 24 '16 09:12

Omar Makled


2 Answers

You can create recursive function using filter() and also continue filtering children if value is Array.

var items = [{
  name: "a1",
  id: 1,
  children: [{
    name: "a2",
    id: 2,
    children: [{
      name: "a3",
      id: 3
    }, ]
  }]
}];

function filterData(data, id) {
  var r = data.filter(function(o) {
    Object.keys(o).forEach(function(e) {
      if (Array.isArray(o[e])) o[e] = filterData(o[e], id);
    })
    return o.id != id
  })
  return r;
}

console.log(filterData(items, 3))
console.log(filterData(items, 2))

Update: As Nina said if you know that children is property with array you don't need to loop keys you can directly target children property.

var items = [{
  name: "a1",
  id: 1,
  children: [{
    name: "a2",
    id: 2,
    children: [{
      name: "a3",
      id: 3
    }, ]
  }]
}];

const filterData = (data, id) => data.filter(o => {
  if (o.children) o.children = filterData(o.children, id);
  return o.id != id
})

console.log(JSON.stringify(filterData(items, 3), 0, 2))
console.log(JSON.stringify(filterData(items, 2), 0, 2))
like image 149
Nenad Vracar Avatar answered Sep 24 '22 18:09

Nenad Vracar


If it's ok for your case to use Lodash+Deepdash, then:

let filtered = _.filterDeep(items,(i)=>i.id!=3,{tree:true});

Here is a demo Codepen

like image 32
Yuri Gor Avatar answered Sep 24 '22 18:09

Yuri Gor