1

I need to search the elements containing the searched text in a parent and child structure, similar to this:

[
  {
    "id": "1",
    "name": "Apple",
    "value": "1",
    "children": [
      {
        "id": "4",
        "name": "iPhone",
        "value": "4",
      }
    ]
  },
  {
    "id": "2",
    "name": "Samsung",
    "value": "2",
    "children": [
      {
        "id": "5",
        "name": "Android",
        "value": "5",
      }
    ]
  },
  {
    "id": "3",
    "name": "AppleX",
    "value": "3",
  }
]

An example: the user searched for the string "Apple", he would need to filter all the elements of this structure that contain this string "Apple".

The search is always based on the object name.

  • 6
    Please add the code you've attempted to your question as a [mcve]. `abc` doesn't exist anywhere in the data you've provided so it's kind of useless as an example. Are you looking at all the property values, or just one like `value`? – Andy Nov 30 '22 at 17:40
  • 1
    `I need x` is not a coding question. – James Nov 30 '22 at 17:54

1 Answers1

0

It also gives nth level depth search result :

let arr = [
  {
    id: "1",
    name: "Name 1",
    value: "1",
    children: [
      {
        id: "4",
        name: "Name one",
        value: "4",
        children: [
          {
            id: "41",
            name: "Name one",
            value: "41",
          },
        ],
      },
    ],
  },
  {
    id: "2",
    name: "Name 2",
    value: "2",
    children: [
      {
        id: "5",
        name: "Name 5 three one",
        value: "5",
      },
    ],
  },
  {
    id: "3",
    name: "Name 3",
    value: "3",
  },
];

let str = "one";

let stack = arr;

let result = [];

while (stack.length) {
  let elem = stack.shift();

  if (elem.children && elem.children.length > 0) {
    stack.push(...elem.children);
  }

  //
  let keys = Object.keys(elem).filter((v) => v != "children");

  keys.map((m) => {
    if (elem[m].includes(str)) {
      delete elem["children"];
      result.push(elem);
    }
  });
  //
}

console.log(result);
Jerry
  • 1,005
  • 2
  • 13