JSFiddle - React, Tailwind, and code Playground
by cmruser
JavaScript
let data = [];
const blocks = [
{
id: 1,
type: 'block',
data: [],
position: 0,
mapToParent: null
},
{
id: 2,
type: 'field',
data: [],
position: 2,
mapToParent: 0
},
{
id: 3,
type: 'block',
data: [],
position: 3,
mapToParent: 0
},
{
id: 4,
type: 'block',
data: [],
position: 4,
mapToParent: 5
},
{
id: 5,
type: 'block',
data: [],
position: 5,
mapToParent: 4
}
];
const fields = [
{
id: 6,
type: 'field',
data: [],
position: 1,
mapToParent: 0
}
];
const form = [...blocks, ...fields];
form.sort((a, b) => a.position - b.position );
console.log(form);
function mapToBlock(array, block) {
var bool = false;
if(block.mapToParent === null) {
bool = true;
array.push({...block});
return;
}
array.find(element => {
if(element.position === block.mapToParent) {
bool = true;
element.data.push({...block});
return;
}
if(element.type === 'block') {
bool = true;
mapToBlock(element.data, block);
}
});
if(!bool) console.warn(`Fail mapToParent: ${block.mapToParent}`, block);
}
form.forEach(block => {
if(block.mapToParent === null) {
data.push({...block});
} else {
mapToBlock(data, block)
}
});
console.log(data);