简体   繁体   中英

Get path of value in object from nested array

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?

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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM