JSFiddle - React, Tailwind, and code Playground

by Nalin Sajwan

JavaScript

let dataArr = [
    {
        "ID": 2,
        "Parent_ID": 1,
        "title": "level 2 section 1"
    },
    {
        "ID": 1,
        "Parent_ID": 0,
        "title": "section 0 level 1"
    },
    {
        "ID": 2,
        "Parent_ID": 0,
        "title": "section 1 level 1"
    },
    {
        "ID": 4,
        "Parent_ID": 3,
        "title": "level 2 section1"
    },
    {
        "ID": 6,
        "Parent_ID": 5,
        "title": "level 3 section 1"
    },
    {
        "ID": 5,
        "Parent_ID": 3,
        "title": "level 2 section2"
    },
    {
        "ID": 3,
        "Parent_ID": 0,
        "title": "level 1 btw 0 and 1 section"
    },
    {
        "ID": 4,
        "Parent_ID": 0,
        "title": "Section 2 level1"
    }
];
let map = {};

dataArr.forEach( (data, index) => {
	data.index = index;
  map[ index ] = [];
});

console.log("dataArr ==> ", dataArr);
console.log("1. map ==> ", JSON.parse(JSON.stringify(map)));

function getParentOfIndexes(index, indexArr) {

	let dataObj = dataArr[ index ];
  
  if (dataObj.Parent_ID > 0) {
  	let parentObj = dataArr.find(v => v.ID === dataObj.Parent_ID);
  	indexArr.push(parentObj.index);
    getParentOfIndexes(parentObj.index, indexArr);
  } else {
  	return indexArr;
  }
};

for (let i in map) {
	let indexes = [];
  
  getParentOfIndexes(i, indexes);
  
  map[ i ] = indexes;
};

console.log("2. map ==> ", map);

let selected = [ 0, 1, 2, 4, 5, 6 ];

console.log("selected ==> ", selected);

let actualSelection = [];

selected.forEach(i => {
	actualSelection.push(i);
  
  actualSelection = actualSelection.concat( map[i] );
})

console.log("actualSelection ==> ", actualSelection);