Recursively Search in JSON or Javascript Object

前端 未结 5 760
甜味超标
甜味超标 2020-12-20 07:08

For example:

[{
    id:\'our-purpose\',
    title:\'Our Purpose\',
    slug:\'/our-purpose\',
    backgroundImage:\'images/bg-our-purpose.jpg\',
    showInNa         


        
5条回答
  •  盖世英雄少女心
    2020-12-20 08:10

    Here's a start (in some mix of JavaScript and pseudocode):

    function createMenu(data) {
        create UL
        for each item in data {
            create LI for item in UL
            if the item has subpages {
                append createMenu(item.subpages) to the LI
            }
        }
        return UL
    }
    
    function findByID(data, id) {
        for each item in data {
            if(item.id==id) {
                return the item
            }
            if item has subpages {
                if findByID(item.subpages, id) is not null, return the result
            }
        }
        return null;
    }
    

提交回复
热议问题