Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How filter in a nested tree object without losing structure in javascript?

To display correctly a Tree view in React, I need to filter a nested tree object.

I find this post : filter nested tree object without losing structure

But actually I would like to do the exactly opposite. For instance, if in my filterData function name === "a3" I would like to keep object with name === "a3"

const result = filterData(items, "a3")
const items = [
  {
    name: "a1",
    id: 1,
    children: [
      {
        name: "a2",
        id: 2,
        children: [
          {
            name: "a3",
            id: 3
          },
          {
            name: "a5",
            id: 4
          }
        ]
      }
    ]
  },
  {
    name: "b2",
    id: 2,
    children: [
      {
        name: "a2",
        id: 2,
        children: [
          {
            name: "a3",
            id: 3
          }
        ]
      },
      {
        name: "a4",
        id: 8
      }
    ]
  }
];
const result = [
  {
    name: "a1",
    id: 1,
    children: [
      {
        name: "a2",
        id: 2,
        children: [
          {
            name: "a3",
            id: 3
          }
        ]
      }
    ]
  },
  {
    name: "b2",
    id: 2,
    children: [
      {
        name: "a2",
        id: 2,
        children: [
          {
            name: "a3",
            id: 3
          }
        ]
      }
    ]
  }
];
like image 461
Vincent Miquel Avatar asked Sep 03 '25 15:09

Vincent Miquel


1 Answers

You could create new objects without mutating the given data and reduce the arrays.

function filter(array, name) {
    return array.reduce((r, { children = [], ...o }) => {
        if (o.name === name) {
            r.push(o);
            return r;
        }
        children = filter(children, name);
        if (children.length) {
            r.push(Object.assign(o, { children }));
        }
        return r;
    }, []);
}    

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

console.log(filter(items, "a2"));
console.log(filter(items, "a3"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 134
Nina Scholz Avatar answered Sep 05 '25 08:09

Nina Scholz