0

How could I get the path to a nested value inside this nested array:

const categories = [
    {
        name: 'category1',
        subcategories: [
            {
                name: 'category2',
                subcategories: [],
            },
            {
                name: 'category3',
                subcategories: [
                    {
                        name: 'category4',
                        subcategories: [],
                    },
                ],
            },
        ],
    },
    {
        name: 'category5',
        subcategories: [],
    },
];

I need to implement a function that will return something like this:

console.log(getCategoryPath(categories, 'category4')); // should output: '/category1/category3/category4'

So far I've got:

const getCategoryPath() = (categories, categoryName) {
    if (category.name === categoryName) {
        path = `/${category.name}`;
    } else {
        category.subcategories.find((firstLevelSubcategory) => {
            if (firstLevelSubcategory.name === categoryName) {
                path = `/${firstLevelSubcategory.name}`;
            } else {
                firstLevelSubcategory.subcategories.find(
                    (secondLevelSubcategory) => {
                        if (secondLevelSubcategory.name === categoryName) {
                            path = `/${secondLevelSubcategory.name}`;
                        }
                    }
                );
            }
        });
    }
}

This prints the matching category name /category4, for example, but I would need to print the whole path to that value /category1/category3/category4.

In this case I'm failing to identify the parent/parents of the matching categoryName. Could I use recursion for this problem and if so, how could I apply it?

1 Answer 1

5

You can apply recursion:

const categories = [ { name: 'category1', subcategories: [ { name: 'category2', subcategories: [], }, { name: 'category3', subcategories: [ { name: 'category4', subcategories: [], }, ], }, ], }, { name: 'category5', subcategories: [], },];

const getNestedPath=(arr,name)=>{
    for(let item of arr){
        if(item.name===name) return `/${name}`;
        if(item.subcategories) {
            const child = getNestedPath(item.subcategories, name);
            if(child) return `/${item.name}${child}`
        }
    }
};

console.log(getNestedPath(categories, 'category4'));

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.