JavaScript
from:
const array = [
{
cantDelete: false,
cantShifLeft: true,
cantShiftDown: false,
cantShiftRight: true,
cantShiftUp: true,
children: ["g12034c6b772_0_5", "g12034c6b772_0_25", "g12034c6b772_0_15"],
displayId: "1",
id: "533c1e97-465e-4f3e-827b-3b6db8e745f4",
idx: 0,
kind: "folder",
order: 1,
parent: null,
title: "test"
},
{
id: "g12034c6b772_0_5",
kind: "slide",
notes: "",
order: 1,
render: {},
title: "Slide 1",
type: "snapshot",
videos: []
},
{
id: "g12034c6b772_0_25",
kind: "slide",
notes: "",
order: 2,
render: {},
title: "Slide 2",
type: "snapshot",
videos: []
},
{
id: "g12034c6b772_0_15",
kind: "slide",
notes: "",
order: 3,
render: {},
title: "Slide 3",
type: "snapshot",
videos: []
},
{
id: "g12034c6b772_0_35",
kind: "slide",
notes: "",
order: 1,
render: {},
title: "Slide 1",
type: "snapshot",
videos: []
}
];
to:
const array = [
{
cantDelete: false,
cantShifLeft: true,
cantShiftDown: false,
cantShiftRight: true,
cantShiftUp: true,
displayId: "1",
id: "533c1e97-465e-4f3e-827b-3b6db8e745f4",
idx: 0,
kind: "folder",
order: 1,
parent: null,
title: "test"
children: [{object}, {object}, {object}],
},
{
id: "g12034c6b772_0_35",
kind: "slide",
notes: "",
order: 1,
render: {},
title: "Slide 1",
type: "snapshot",
videos: []
}
];
After creating helper function for finding object and splicing it out of the array, we can iterate the array, pushing to his children the actual children matching the id. Just look at the code.
const array = [{
cantDelete: false,
cantShifLeft: true,
cantShiftDown: false,
cantShiftRight: true,
cantShiftUp: true,
children: ["g12034c6b772_0_5", "g12034c6b772_0_25", "g12034c6b772_0_15"],
displayId: "1",
id: "533c1e97-465e-4f3e-827b-3b6db8e745f4",
idx: 0,
kind: "folder",
order: 1,
parent: null,
title: "test"
},
{
id: "g12034c6b772_0_5",
kind: "slide",
notes: "",
order: 1,
render: {},
title: "Slide 1",
type: "snapshot",
videos: []
},
{
id: "g12034c6b772_0_25",
kind: "slide",
notes: "",
order: 2,
render: {},
title: "Slide 2",
type: "snapshot",
videos: []
},
{
id: "g12034c6b772_0_15",
kind: "slide",
notes: "",
order: 3,
render: {},
title: "Slide 3",
type: "snapshot",
videos: []
},
{
id: "g12034c6b772_0_35",
kind: "slide",
notes: "",
order: 1,
render: {},
title: "Slide 1",
type: "snapshot",
videos: []
}
];
function find(array, id) {
return array.find((obj) => obj.id == id);
}
function extract(array, id) {
var obj = find(array, id);
array.splice(array.indexOf(obj), 1);
return obj;
}
function compact(array) {
array.forEach(function(item) {
if (item.kind == "folder") {
var children = [];
item.children.forEach(function(id) {
children.push(extract(array, id));
})
item.children = children;
}
})
return array;
}
console.log(compact(array))
.as-console-wrapper {
max-height: 100% !important;
}