After my glorious fails with loops I came here for help.
Basically I want to "add new level" to my target JSON, based on data from source.
Base JSON:
var base = [
{
children: [
{
children: [],
parent: "ROOT",
title: "Tenant1",
typeName: "Tenants"
},
{
children: [],
parent: "ROOT",
title: "Tenant2",
typeName: "Tenants"
}
],
parent: null,
title: "ROOT",
typeName: null,
}
];
Target JSON:
var target = [
{
children: [
{
children: [
{
children: [],
parent: "Tenants",
title: "Tenant1",
typeName: "Tenants"
},
{
children: [],
parent: "Tenants", // <---- here
title: "Tenant2",
typeName: "Tenants"
}
],
parent: "ROOT", // <---- here
title: "Tenants",
typeName: "Tenants"
}
],
parent: null,
title: "ROOT",
typeName: null
}
];
The new level needs to have parent as ROOT, and "old" children (now leafs) have to have parent set to their "typeName".
Hope this works fine for you. I've made a recursive function that once it finds the parent of the element that you pass to add, it passes the children of the parent element to the current element and adds the new element.
var base = [ { children: [ { children: [], parent: "ROOT", title: "Tenant1", typeName: "Tenants" }, { children: [], parent: "ROOT", title: "Tenant2", typeName: "Tenants" } ], parent: null, title: "ROOT", typeName: null, }, ]; let element = { parent: "ROOT", title: "Tenants", typeName: "Tenants" }; function addNewLevel(list, element) { if(list.length) { for (var i = 0; i < list.length; i++) { if(list[i].title === element.parent) { element.children = list[i].children; for (var j = 0; j < element.children.length; j++) { element.children[j].parent = element.title; } list[i].children = [element]; } else if(list[i].children.length) { let newList = addNewLevel(list[i].children, element); list[i].children = newList; return list[i]; } } return list; } } console.log('New Level List', addNewLevel(base, element));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.