const obj = {
id: 1,
parentId: 0,
childGroups: [
{
id: 2,
parentId: 1,
},
{
id: 3,
parentId: 1,
childGroups: [
{
id: 6,
parentId: 3,
},
{
id: 7,
parentId: 3,
},
]
},
{
id: 4,
parentId: 1,
},
{
id: 5,
parentId: 1,
},
]
}
function doSmth(obj) {
console.log(obj.id)
}
function isRightObj(obj) {
return obj.id === 6
}
function reqursive(obj) {
if ( isRightObj(obj) ) {
doSmth(obj)
}
const childs = obj.childGroups
if (childs && Array.isArray(childs)) {
childs.forEach(reqursive)
}
}
reqursive(obj)
function getById( obj, id) {
var i, found;
if( obj.id === id) return obj;
if( obj.hasOwnProperty('childGroups')) {
for( i in obj.childGroups) {
if( found = getById( obj.childGroups[i], id)) return found;
}
}
return;
}
getById( obj,3) // {"id":3,"parentId":1,"childGroups":[{"id":6,"parentId":3},{"id":7,"parentId":3}]}