Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
convert data from list to tree format
let data = [{
"counterpartyGroupId": 10,
"counterpartyGroupName": "Офисные сооружения",
"counterpartyGroupTypeId": 3,
"counterpartyGroupRemark": "Офисы",
"counterpartyGroupParentId": 0
},
{
"counterpartyGroupId": 11,
"counterpartyGroupName": "Страховые компании",
"counterpartyGroupTypeId": 5,
"counterpartyGroupRemark": "Страховые",
"counterpartyGroupParentId": 0
},
{
"counterpartyGroupId": 12,
"counterpartyGroupName": "Вина",
"counterpartyGroupTypeId": 2,
"counterpartyGroupRemark": "Вина Молдовы",
"counterpartyGroupParentId": 15
},
{
"counterpartyGroupId": 13,
"counterpartyGroupName": "Трактора и машины",
"counterpartyGroupTypeId": 5,
"counterpartyGroupRemark": "Комбайны и трактора",
"counterpartyGroupParentId": 11
},
{
"counterpartyGroupId": 14,
"counterpartyGroupName": "Диллер автозапчастей",
"counterpartyGroupTypeId": 5,
"counterpartyGroupRemark": "Кузовные детали",
"counterpartyGroupParentId": 13
},
{
"counterpartyGroupId": 15,
"counterpartyGroupName": "Транспортная компания",
"counterpartyGroupTypeId": 3,
"counterpartyGroupRemark": "работают в Киеве",
"counterpartyGroupParentId": 10
},
{
"counterpartyGroupId": 16,
"counterpartyGroupName": "Строители",
"counterpartyGroupTypeId": 3,
"counterpartyGroupRemark": "My friend!!",
"counterpartyGroupParentId": 2
},
{
"counterpartyGroupId": 17,
"counterpartyGroupName": "Никуда не ехать",
"counterpartyGroupTypeId": 2,
"counterpartyGroupRemark": "Лучшие на рынке",
"counterpartyGroupParentId": 13
},
{
"counterpartyGroupId": 18,
"counterpartyGroupName": "Лес и дрова",
"counterpartyGroupTypeId": 5,
"counterpartyGroupRemark": "Приятно с ним работать",
"counterpartyGroupParentId": 0
}
];
function findChildItems(id, data){
let result = [];
data.forEach(item => {
if(item.counterpartyGroupParentId == id){
result.push({
id: item.counterpartyGroupId,
name: item.counterpartyGroupName,
children: findChildItems(item.counterpartyGroupId, data)
});
}
});
return result;
}
console.log(JSON.stringify(findChildItems(0, data)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment