JSFiddle - React, Tailwind, and code Playground
JavaScript
var data = [
{
"item_id": null,
"parent_id": "none",
"depth": 0,
"left": "1",
"right": 4
},
{
"item_id": "1",
"parent_id": null,
"depth": 1,
"left": 2,
"right": 3
}
/* ,{ // sub data test
"data2": 2,
"subData": [
{
"item_id": null,
"parent_id": "none",
"depth": 0,
"left": "1",
"right": 4
},
{
"item_id": "1",
"parent_id": null,
"depth": 1,
"left": 2,
"right": 3
}
]
}*/
];
function isArray($obj) {
return Object.prototype.toString.call($obj) === '[object Array]';
}
function subObject(data) {
if(isArray(data)){
return (subArray(data));
}
var result = [];
for (var i in data) {
var item = data[i];
if (item === null) { // null type is ojbect ..!
result.push(item);
} else if (isArray(item)) {
result.push(subArray(item));
} else if (typeof item === 'object') {
result.push(subObject(item));
} else {
result.push(item);
}
}
return result;
}
function subArray(data) {
var result = [];
for (var i = 0; i < data.length; i++) {
var item = data[i];
if (item === null) { // null type is ojbect ..!
result.push(item);
} else if (isArray(item)) {
result.push(subArray(item));
} else if (typeof item === 'object') {
result.push(subObject(item));
} else {
result.push(item);
}
}
return result;
}
var r = subObject(data);
console.log(r);