search

Home  >  Q&A  >  body text

javascript - Question about json array recursion

var arr=[{

    name:"总队",
    id:"1",
    alias:"zongdui",
    children:[{
        name:"第一支队",
        id:"2",
        parent_id:"1",
        children:[
            {
                name:"第一大队",
                id:"4",
                parent_id:"2"    
            }
        ]},
        {
        name:"第二支队",
        id:"3",
        parent_id:"1",
        children:[
            {
                name:"第二大队",
                id:"5",
                parent_id:"2"
            }
        ]
    }]  

}]

How to recursively get name and id from this json? Request the code

PHP中文网PHP中文网2864 days ago419

reply all(4)I'll reply

  • 高洛峰

    高洛峰2017-05-16 13:01:57

    Using recursion to implement

    var arr = [{
        name:"总队",
        id:"1",
        alias:"zongdui",
        children:[{
            name:"第一支队",
            id:"2",
            parent_id:"1",
            children:[
                {
                    name:"第一大队",
                    id:"4",
                    parent_id:"2"    
                }
            ]},
            {
            name:"第二支队",
            id:"3",
            parent_id:"1",
            children:[
                {
                    name:"第二大队",
                    id:"5",
                    parent_id:"2"
                }
            ]
        }]  
    }]; 
    
    function headFor(o, cb){
        if (!o) return; 
    
        o.forEach(child => {
            cb(child); 
            if (child.children) {
                headFor(child.children, cb);    
            }
        });
    }
    
    var res = []; 
    headFor(arr, function(o){
        var temp = {
            name: o.name, 
            id: o.id,
            parent_id: o.id 
        }; 
        res.push(temp); 
    }); 
    
    res.forEach(e => console.log(e)); 
    console.log(JSON.stringify(res)); 
    

    Link

    I answered an almost identical question. . .
    /q/10...

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-16 13:01:57

    var ret = [];
    while (arr != []) {
        ret.push({
            'name': arr[0]['name'],
            'id': arr[0]['id'],
        )
        arr = arr['children'];
    }
    console.log(ret);

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-16 13:01:57

    arr2 = []
    function arr_mat(arr){
        for(var i=0;i<arr.length;i++){
            if(arr[i].children.length > 0){
            //     // arr2.push({
            //     //     'name':arr[i].children.name
            //     // });
                console.log(arr[i].children);
    
                arr_mat(arr[i].children);
            }
        }
    }
    arr_mat(arr);
    

    Why can’t I do this

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-16 13:01:57

    You can use the json_decode function to convert the json string into an array operation

    reply
    0
  • Cancelreply