var categories = [ {id:1, parent:null}, {id:2, parent:1}, {id:3, parent:null}, {id:4, parent:2}, {id:5, parent:2}, {id:6, parent:3}, {id:7, parent:null}, {id:8, parent:7}, {id:9, parent:5}, ]; var categories_map = {} categories.forEach(function (category) { categories_map[category.id] = category; }); console.log(categories_map); categories.forEach(function (category) { if (category.parent) { categories_map[category.parent]['subcategories'] = categories_map[category.parent]['subcategories'] || []; categories_map[category.parent]['subcategories'].push(category); } }); console.log(categories); categories = categories.filter(function (category) { return !category.parent; }); console.log(JSON.stringify(categories, null, ' '));