0

I have nested array of objects and want to filter it based on a variable.

let arrayOfObjects = [
    {
        "title": "title1",
        "link": "link1.html",
        "level-one": [
            {
                "title": "title2",
                "link": "link2.html",
                "level-two": [
                    {
                        "title": "title3",
                        "link": "link3.html"
                    }
                ]
            }
        ]
    },
    {
        "title": "title4",
        "link": "link4.html"
    },
    {
        "title": "title5",
        "link": "link5.html",
        "level-one": [
            {
                "title": "title6",
                "link": "link6.html"
            }
        ]
    }
]

I wanted to filter out the objects that has the link, say for eg. link5.html, When I try to filter it only checks the top level and not into level-one and level-two.

Below is the code that I tried.

let currentLink = "link5.html"
arrayOfObjects.filter(i => i.link === currentLink)
arrayOfObjects.filter(r => r['level-one'].some(i => i.link === currentLink));

The first one checks only the parent level and the second one checks only inside level-one. But I want to check all the levels. Any suggestions would be helpful

Expected output should return the complete object that has the matched link eg for link5.html it should return

{
        "title": "title5",
        "link": "link5.html",
        "level-one": [
            {
                "title": "title6",
                "link": "link6.html"
            }
        ]
}
  • What is the expected output? Will the output include the path to the node? Will it include the potential children of the node? Can you give the expected output if the current link is "link5.html"? See the link in the blue banner at the top. – trincot Jul 14 '23 at 09:11
  • Thank you @trincot. Let me try the solutions from the blue banner – user3699344 Jul 14 '23 at 09:17

0 Answers0