Convert nested Json to flat Json with parentId to every node
You could take an iterative and recursive approach by using a function which takes an array and a parent id for the actual level.
If a property starts with child
, it calls the function again with the actual _id
and pushes all items to the result set.
function getFlat(array, parentid) { return array.reduce((r, o) => { var temp = {}; r.push(temp); Object.entries(o).forEach(([k, v]) => { if (k.startsWith('child')) { r.push(...getFlat(v, o._id)); } else { temp[k] = v; } }); temp.parentid = parentid; return r; }, []);}var data = [{ child1: [{ _type: "EntityChild1", name: "Test222", _id: 2 }], child2: [{ _type: "EntityChild2", name: "Test333", _id: 3, child2_child1: [{ _type: "EntityChild2_1", name: "Test444", _id: 6, child2_child1_child1: [{ _type: "EntityChild2_1_1", name: "Test555", _id: 7 }] }] }], _type: "EntityParent", name: "Test000", _id: 1, child3: [{ _type: "EntityChild3", name: "Test111", _id: 4 }], child4: [{ _type: "EntityChild4", name: "Test666", _id: 5 }] }], flat = getFlat(data, -1);console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }