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
曾经蜡笔没有小新2017-05-19 10:13:14
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梦2017-05-19 10:13:14
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 ","