[
{
"h1": "h001",
"h2": "z001"
},
{
"h1": "h002",
"h2": "z002"
},
{
"h1": "h003",
"h2": "z003"
}
]
[{
"h1": "h001",
"h2": "z001",
"children": {
"h1": "h002",
"h2": "z002",
"children": {
"h1": "h003",
"h2": "z003"
}
}
}]
const arrToSinglyLinkedList = (arr, nextKey = 'next') =>
arr.reduceRight((acc, n) => ({ ...n, [nextKey]: acc }), null);
function arrToSinglyLinkedList(arr, nextKey = 'next') {
let list = null;
for (let i = arr.length; i--;) {
const node = Object.assign({}, arr[i]);
node[nextKey] = list;
list = node;
}
return list;
}
const list = arrToSinglyLinkedList(arr, 'child');
const example = (arr) => {
let result = [];
if (Array.prototype.hasOwnProperty.call(arr, 0) && arr[0] instanceof Object)
result.push(arr[0]);
let lastObj = result[0];
for (let i = 1; i < arr.length; ++i) {
const el = arr[i];
if (el && el instanceof Object) {
lastObj.children = el;
lastObj = el;
}
}
return result;
}