I am implementing multi level datatable without using any plugin or library. I want to implement based on javaScript, JQuery or angular js. I checked one below links,
The simplest way I can think of accomplishing this with vanilla Javascript would be a modified depth first traversal of an object:
function renderJSON(json) {
const wrapper = document.createElement('div');
const stack = [{
node: json,
name: 'root',
parentEl: wrapper
}];
while (stack.length > 0) {
let current = stack.pop();
let currentObj = current.node;
let currentParentEl = current.parentEl;
let level = document.createElement('div');
level.classList.add('level');
level.textContent = current.name + ': ';
if (currentObj.renderContent) {
// render custom html content
currentObj.renderContent(level);
} else if (!(currentObj instanceof Object)) {
level.textContent += currentObj;
}
currentParentEl.append(level);
if (currentObj instanceof Object) {
let keys = Object.keys(currentObj);
if (!currentObj.skipChildren) {
// push in reverse to preserve key order
for (let i = keys.length - 1; i >= 0; i--) {
let key = keys[i];
let node = currentObj[key];
stack.push({
node: node,
name: key,
parentEl: level
});
}
}
}
}
return wrapper;
}
// Example Use Case:
const Permissions = function Permissions() {
this.skipChildren = true;
this.view = false;
this.edit = false;
this.delete = false;
};
Permissions.prototype = {
renderContent(el) {
const fields = ['view', 'edit', 'delete'];
for (let field of fields) {
const label = document.createElement('label');
label.textContent = field;
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = this[field];
label.appendChild(checkbox);
el.appendChild(label);
}
}
};
const rendered = renderJSON({
element1: {
a: 4,
b: 6,
c: 24,
element1a: {
a: 'hello'
}
},
element2: {
a: 'abc',
permissions: new Permissions()
},
element3: ["first", "second", "third"]
});
document.body.append(rendered);
.level {
margin-left: 1em;
}
There's a lot of different ways you could branch off of this code depending on your needs. Since you're given a JSON string to begin with, you'll need to find some way to convert that into a Javascript object that will produce the result you want.