javascript - Four layers of tree data are obtained from the interface, and a method is needed to match any item in any layer.
PHP中文网
PHP中文网 2017-05-19 10:11:14
0
2
431

It may be a bit convoluted, but the specifics are like this. A data is received from the interface, and the structure is roughly like this:

[
    {
        id: '1',
        name: '',
        child: [
            {id: '5',
                name: 'aaa',
                child: [
                    {
                        id: '1',
                        name: 'aaa',
                        child: [
                            {
                                id: '1',
                                name: 'aaa',
                                child: [
                                    
                                ]
                            }
                        ]
                    }
                ]
            }
        ]    
    },
    {
        id: '2',
        name: '',
        child: [
            
        ]
    }
]

Each piece of data in each layer has an independent ID, and then there is a child field corresponding to the second layer of data, and the second layer of data also has a child field corresponding to the third layer of data, etc...

Is there a more efficient way to obtain the corresponding name from this tree data through a specified id? Find a wrapper function

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
曾经蜡笔没有小新

I wrote a demo based on your request and the data sample you provided. I don’t know if it meets your requirements. Return the current object through a specified id

    var data = 你的数据样本;
    var Result;
    function demo( data, id ) {
        for (var i = 0; i < data.length; i++) {
            if ( data[ i ].id == id ) {
                Result = data[ i ];
                break;
            }else if ( data[ i ].child.length && !Result ) {
                demo( data[ i ].child, id );
            };
        };
        return Result;
    }
    console.log(demo( data, 3 ));

Run result
Note: demo( data, id ) 中的 id must be unique

过去多啦不再A梦

The right way: Recursion;
The wrong way: After object JSON.Stringify, after matching "id":"xx" with regular expression, get the first string between "name:" and ","

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template