Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
Infinite nested elements in json file and How to get elements?

This is my JSON file:

layers :[
    {
      key: "1",
      title: "Computer Science",
      expanded: false,
      subLayer: [
        {
          key: "a",
          title: "Programming Language",
          expanded: false,
          subLayer: [
            {
              key: "a.1",
              title: "HTML",
              expanded: false,
              subLayer: [],
            },
            {
              key: "a.2",
              title: "CSS",
              expanded: false,
              subLayer: [],
            },
          ],
        },
      ],
    },
  ]

Images:

enter image description here

My question is: When I search Programming Language and Computer Science it appears but if you search for parts in subLayer elements such as HTML and CSS it doesn't appear or can't, why is that? And what needs to be improved from my coding? If I'm writing my code:

const filteredData = data.layers.filter((el) => {
    if (props.input === '') {
      return el
    }
    return el.title.toLowerCase().includes(props.input) || el.subLayer.findIndex(x => x.title.toLowerCase().includes(props.input)) >= 0
}) 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are only searching the top-most subLayer, which is el.subLayer. You need to search the nested subLayer also. This can be done recursively by looking at whether the current object's title includes your input, and if it doesn't you can check if some object in your subLayer includes the input in the title by recursively calling the search function:

const layers = [{ key: "1", title: "Computer Science", expanded: false, subLayer: [{ key: "a", title: "Programming Language", expanded: false, subLayer: [{ key: "a.1", title: "HTML", expanded: false, subLayer: [], }, { key: "a.2", title: "CSS", expanded: false, subLayer: [], }, ], }, ], }, ];

const hasKeyword = (obj, keyword) => {
  return obj.title.toLowerCase().includes(keyword) || obj.subLayer.some(nested => hasKeyword(nested, keyword));
}

const search = (layers, keyword) => {
  return layers.filter(obj => hasKeyword(obj, keyword));
}

const res = search(layers, "css");
console.log(res);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!