Flatten Nested Objects and Output Array - javascript

I have a deeply nested object that has the following schema:
const data = {
Car1: {
key: "Car",
value: "1",
child: {
Driver1: {
key: "Driver",
value: "1",
child: {
Trip1: {
key: "Trip",
value: 1,
metrics: { distance: 1, time: 2 }
}
}
},
Driver2: {
key: "Driver",
value: "2",
child: {
Trip1: {
key: "Trip",
value: 1,
metrics: { distance: 3, time: 4 }
},
Trip2: {
key: "Trip",
value: 2,
metrics: { distance: 5, time: 6 }
}
}
}
}
}
}
That I need to flatten into a singular array of objects, with each object in the array having all the properties of its direct child(ren).
Each nested object child is a Record of objects that have properties key and value.
The last object in the nested structure always has a property called metrics that should be flattened into the object as well.
So the output would look something like:
[
{ Car: 1, Driver: 1, Trip: 1, distance: 1, time: 2 },
{ Car: 1, Driver: 2, Trip: 1, distance: 3, time: 4 },
{ Car: 1, Driver: 2, Trip: 2, distance: 5, time: 6 }
]
I have tried the following code but it only captures one level of depth in the child tree:
private flattenOutput(child: Record<string, OutputChild> = this.output): any[] {
console.log('flattening', Object.keys(child));
return Object.values(child).map((child) => {
return Object.assign(
{},
{ [child.key]: child.value },
...this.flattenOutput(child.child),
child.metrics || {},
);
}, {});
}

By having correct nested objects, you could take a recursive approach and collect key/value and return a flat array with wanted objects.
const
collect = (object, temp = {}) => Object
.values(object)
.flatMap(({ key, value, child, metrics }) => child
? collect(child, { ...temp, [key]: value })
: { ...temp, [key]: value , ...metrics }
),
data = { Car1: { key: "Car", value: "1", child: { Driver1: { key: "Driver", value: "1", child: { Trip1: { key: "Trip", value: 1, metrics: { distance: 1, time: 2 } } } }, Driver2: { key: "Driver", value: "2", child: { Trip1: { key: "Trip", value: 1, metrics: { distance: 3, time: 4 } }, Trip2: { key: "Trip", value: 2, metrics: { distance: 5, time: 6 } } } } } } },
result = collect(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

I will do that this way :
data =
{ Car1: { key: "Car", value: "1", child:
{ Driver1: { key: "Driver", value: "1", child:
{ Trip1: { key: "Trip", value: 1, metrics: { distance: 1, time: 2} }
} }
, Driver2:
{ key: "Driver", value: "2", child:
{ Trip1: { key: "Trip", value: 1, metrics: { distance: 3, time: 4} }
, Trip2: { key: "Trip", value: 2, metrics: { distance: 5, time: 6} }
} } } } }
let result = []
for (let Car in data )
for (let Driver in data[Car].child)
for (let Trip in data[Car].child[Driver].child)
result.push(
{ Car : data[Car].value
, Driver : data[Car].child[Driver].value
, Trip : data[Car].child[Driver].child[Trip].value
, distance : data[Car].child[Driver].child[Trip].metrics.distance
, time : data[Car].child[Driver].child[Trip].metrics.time
})
console.log( result )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

reducing nested object key value inside an an array

i have the following arrays
array1 = [
{a:{key:1 , value: 10} , b:{key:1 , value:12} , c:{key:1 , value: 5} , d:{key:1 , value:2}},
{a:{key:2 , value: 10} , b:{key:2 , value:12} , c:{key:2 , value: 5} , d:{key:2 , value:2}},
{a:{key:3 , value: 10} , b:{key:3 , value:12} , c:{key:3 , value: 5} , d:{key:3 , value:2}},
]
array2 = [
{a:{key:1 , value: 10} , b:{key:1 , value:12} , c:{key:1 , value: 5} , d:{key:1 , value:2}},
{a:{key:2 , value: 10} , b:{key:2 , value:12} , c:{key:2 , value: 5} , d:{key:2 , value:2}},
{a:{key:4 , value: 10} , b:{key:4 , value:12} , c:{key:4 , value: 5} , d:{key:4 , value:2}},
]
reduced array based on key should look like this:
combinedArray= [
{a:{key:1 , value: 20} , b:{key:1 , value:24} , c:{key:1 , value: 10} , d:{key:1 , value:4}},
{a:{key:2 , value: 20} , b:{key:2 , value:24} , c:{key:2 , value: 10} , d:{key:2 , value:4}},
{a:{key:3 , value: 10} , b:{key:3 , value:12} , c:{key:3 , value: 5} , d:{key:3 , value:2}},
{a:{key:4 , value: 10} , b:{key:4 , value:12} , c:{key:4 , value: 5} , d:{key:4 , value:2}},
]
first i tried to merge the two arrays using const mergedArray = [...array1, ...array2]
now i want to check for key duplicates. for example, if there is key1 in both array1 and array2, remove the duplicates then combine the values of that key.
this is what i have tried but it is only iterating through a.key only:
function kdeAdder(param) {
const array = [param.a]
let tempHistory = [];
for(let x=0;x<array.length;x++){
array[x].forEach((item)=>{
let noMatch = true;
if(tempHistory.length > 0) {
tempHistory.forEach((tempItem, i)=>{
if(item.key === tempItem.key) {
tempHistory[i].value += item.value;
noMatch = !noMatch;
}
});
}
return (noMatch) ? tempHistory.push(item) : null;
});
}
return tempHistory;
}
kdeAdder(mergedArray);
As you confirmed the key inner property is commonly shared by the four "a", "b", "c", "d" objects in an outer object, the a.key value can be used to identify which outer objects should merge.
You could group all objects (irrespective of whether they occur in array1 or array2) by that a.key, and then aggregate objects that occur in the same group. Both of these actions can be accomplished with a reduce call:
const aggregate = (objects) =>
objects.reduce((x, y) => ({
a: { key: x.a.key, value: x.a.value + y.a.value },
b: { key: x.b.key, value: x.b.value + y.b.value },
c: { key: x.c.key, value: x.c.value + y.c.value },
d: { key: x.d.key, value: x.d.value + y.d.value },
}));
const merge = (array1, array2) =>
Object.values(array1.concat(array2).reduce((acc, obj) => {
(acc[obj.a.key] ??= []).push(obj);
return acc;
}, {})).map(aggregate);
const array1 = [
{a:{key:1 , value: 10} , b:{key:1 , value:12} , c:{key:1 , value: 5} , d:{key:1 , value:2}},
{a:{key:2 , value: 10} , b:{key:2 , value:12} , c:{key:2 , value: 5} , d:{key:2 , value:2}},
{a:{key:3 , value: 10} , b:{key:3 , value:12} , c:{key:3 , value: 5} , d:{key:3 , value:2}},
];
const array2 = [
{a:{key:1 , value: 10} , b:{key:1 , value:12} , c:{key:1 , value: 5} , d:{key:1 , value:2}},
{a:{key:2 , value: 10} , b:{key:2 , value:12} , c:{key:2 , value: 5} , d:{key:2 , value:2}},
{a:{key:4 , value: 10} , b:{key:4 , value:12} , c:{key:4 , value: 5} , d:{key:4 , value:2}},
]
console.log(merge(array1, array2));
You can first reduce the output to a single object since its a sort of accumulation of numbers, and then get the format you want as the second step.
const array1 = [ { a: { key: 1, value: 10 }, b: { key: 1, value: 12 }, c: { key: 1, value: 5 }, d: { key: 1, value: 2 }, }, { a: { key: 2, value: 10 }, b: { key: 2, value: 12 }, c: { key: 2, value: 5 }, d: { key: 2, value: 2 }, }, { a: { key: 3, value: 10 }, b: { key: 3, value: 12 }, c: { key: 3, value: 5 }, d: { key: 3, value: 2 }, }, ]; const array2 = [ { a: { key: 1, value: 10 }, b: { key: 1, value: 12 }, c: { key: 1, value: 5 }, d: { key: 1, value: 2 }, }, { a: { key: 2, value: 10 }, b: { key: 2, value: 12 }, c: { key: 2, value: 5 }, d: { key: 2, value: 2 }, }, { a: { key: 4, value: 10 }, b: { key: 4, value: 12 }, c: { key: 4, value: 5 }, d: { key: 4, value: 2 }, }, ];
const mergedArray = [...array1, ...array2];
const keys = []
const reducedOutput = mergedArray.reduce((prev, curr) => {
Object.entries(curr).forEach(([mainKey, { key, value }]) => {
// mainKey is a, b, c, d in your case
if (!prev[mainKey]) {
prev[mainKey] = {};
}
// key is 1, 2, 3, 4 in your case
if (!keys.includes(key)) {
keys.push(key)
}
prev[mainKey][key] = prev[mainKey][key]
? prev[mainKey][key] + value
: value;
});
return prev;
}, {});
const output = keys.map(key => {
const obj = {}
Object.entries(reducedOutput).forEach(([k, v]) => {
obj[k] = {key, value: v[key]}
})
return obj
})
console.log(output)
This will work with any other keys for a, b, c, d keys and 1, 2, 3, 4 keys you have used in two levels.
Using Object.entries(), Array.prototype.reduce(), Array.prototype.forEach(), and Array.prototype.map()
The following provided code implements an approach which tries to find a balance in between 1st being agnostic to any array item's current and future structure except for both property names, key and value, of any array item's second level structure and 2nd how to handle the merger of other unknown second level data.
Therefore the general approach creates an object based lookup from the shorter sourceList where each item gets referred to via the value of its second level key property, whereas the longer targetList will be reduced in order to create the final result of merged items from both arrays.
Since approach and implementation are unaware of an items first level structure, one has to reduce again all of a currently processed item's entries. For each of a target item's unknown entry one can rely on such an entry's 2nd level properties, key and value. From all the available data, either known or unknown, one can aggregate the common merger of both the source- and the target-item; their values will be totaled and both of their unknown rest data will be merged by spread syntax, where the latter is the approach's trade off/compromise.
function aggregateFirstValueKeyBasedLookup(lookup, item) {
lookup[Object.values(item)[0]?.key ?? ''] = item;
return lookup;
}
function createKeyBasedValueMergerFromSourceLookup(
{ lookup = {}, result = [] }, targetItem, idx, arr,
) {
let currentLookupKey;
result.push(Object
.entries(targetItem)
.reduce((merger, [
targetEntryKey, {
key, value: targetEntryValue = 0, ...targetEntryRest
}
]) => {
currentLookupKey = key;
const sourceItem = lookup[key] ?? {};
const {
value: sourceEntryValue = 0, ...sourceEntryRest
} = sourceItem[targetEntryKey] ?? {};
return Object.assign(merger, {
[ targetEntryKey ]: {
key,
value: (targetEntryValue + sourceEntryValue),
...targetEntryRest,
...sourceEntryRest,
},
});
}, {})
);
// delete already processed source-items from lookup.
Reflect.deleteProperty(lookup, currentLookupKey);
if (idx >= arr.length - 1) {
// finalize the result by ...
result.push(
// ...pushing all of the lookup's
// unprocessed source-items.
...[...Object.values(lookup)]
);
}
return { lookup, result };
}
const array1 = [{
a: { key: 1, value: 10 }, b: { key: 1, value: 12 }, c: { key: 1, value: 5 }, d: { key: 1, value: 2 }
}, {
a: { key: 2, value: 10 }, b: { key: 2, value: 12 }, c: { key: 2, value: 5 }, d: { key: 2, value: 2 }
}, {
a: { key: 3, value: 10 }, b: { key: 3, value: 12 }, c: { key: 3, value: 5 }, d: { key: 3, value: 2 }
}];
const array2 = [{
a: { key: 1, value: 10 }, b: { key: 1, value: 12 }, c: { key: 1, value: 5 }, d: { key: 1, value: 2 }
}, {
a: { key: 2, value: 10 }, b: { key: 2, value: 12 }, c: { key: 2, value: 5 }, d: { key: 2, value: 2 }
}, {
a: { key: 4, value: 10 }, b: { key: 4, value: 12 }, c: { key: 4, value: 5 }, d: { key: 4, value: 2 }
}];
const [ targetList, sourceList ]
= [array1, array2].sort((a, b) => b.length - a.length);
const sourceLookup = sourceList
.reduce(aggregateFirstValueKeyBasedLookup, Object.create(null));
console.log({ sourceLookup });
const { result: mergedItemList } = targetList
.reduce(createKeyBasedValueMergerFromSourceLookup, {
lookup: sourceLookup, result: [],
});
console.log({ mergedItemList });
// - changed item structure which keeps
// just the most necessary pattern.
const newItemStructureList1 = [{
quick: { key: 'foo', value: 33, biz: 'biz' },
brown: { key: 'foo', value: 22, baz: 'baz' },
fox: { key: 'foo', value: 11, buzz: 'buzz' },
}, {
quick: { key: 'bar', value: 11, baz: 'baz' },
brown: { key: 'bar', value: 33, biz: 'biz' },
fox: { key: 'bar', value: 22, booz: 'booz' },
}, {
quick: { key: 'baz', value: 22, baz: 'baz' },
brown: { key: 'baz', value: 11, biz: 'biz' },
fox: { key: 'baz', value: 33, booz: 'booz' },
}];
const newItemStructureList2 = [{
brown: { key: 'foo', value: 11, baz: 'baz' },
fox: { key: 'foo', value: 33, booz: 'booz' },
quick: { key: 'foo', value: 22, baz: 'baz' },
}, {
fox: { key: 'baz', value: 33, buzz: 'buzz' },
quick: { key: 'baz', value: 11, biz: 'biz' },
brown: { key: 'baz', value: 33, baz: 'baz' },
}];
const [ target, source ]
= [newItemStructureList1, newItemStructureList2].sort((a, b) => b.length - a.length);
const lookup = source
.reduce(aggregateFirstValueKeyBasedLookup, Object.create(null));
console.log({ lookup });
const { result: mergedItems } = target
.reduce(createKeyBasedValueMergerFromSourceLookup, { lookup, result: [] });
console.log({ mergedItems });
.as-console-wrapper { min-height: 100%!important; top: 0; }
You could group with the key property and the outer property.
const
array1 = [{ a: { key: 1, value: 10 }, b: { key: 1, value: 12 }, c: { key: 1, value: 5 }, d: { key: 1, value: 2 } }, { a: { key: 2, value: 10 }, b: { key: 2, value: 12 }, c: { key: 2, value: 5 }, d: { key: 2, value: 2 } }, { a: { key: 3, value: 10 }, b: { key: 3, value: 12 }, c: { key: 3, value: 5 }, d: { key: 3, value: 2 } }],
array2 = [{ a: { key: 1, value: 10 }, b: { key: 1, value: 12 }, c: { key: 1, value: 5 }, d: { key: 1, value: 2 } }, { a: { key: 2, value: 10 }, b: { key: 2, value: 12 }, c: { key: 2, value: 5 }, d: { key: 2, value: 2 } }, { a: { key: 4, value: 10 }, b: { key: 4, value: 12 }, c: { key: 4, value: 5 }, d: { key: 4, value: 2 } }],
result = Object.values([...array1, ...array2].reduce((r, o) => {
Object.entries(o).forEach(([k, { key, value }]) => {
r[key] ??= {};
r[key][k] ??= { key, value: 0 };
r[key][k].value += value;
});
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Filter 2 arrays to check if parent child

I have first array -
let parent = [
{
id:1,
value:"ABC",
},
{
id:2,
value:"DEF",
},
{
id:3,
value:"GHI",
},
{
id:4,
value:"JKL",
},
{
id:5,
value:"MNO",
},
{
id:6,
value:"PQR",
},
]
And 2nd Array Object -
let child = [
{
childid:1,
value:"ABC",
},
{
childid:2,
value:"DEF",
},
{
childid:10,
value:"GHI",
},
]
From parent array I want to select all those elements whose id matches with childid from child array.
I tried -
parent.filter(x=>x.id==child.each(y=>y.childid))
But its not working
You can use some() to do it
let parent = [
{
id:1,
value:"ABC",
},
{
id:2,
value:"DEF",
},
{
id:3,
value:"GHI",
},
{
id:4,
value:"JKL",
},
{
id:5,
value:"MNO",
},
{
id:6,
value:"PQR",
},
]
let child = [
{
childid:1,
value:"ABC",
},
{
childid:2,
value:"DEF",
},
{
childid:10,
value:"GHI",
},
]
let result = parent.filter(p => child.some(a => a.childid == p.id ))
console.log(result)
using Flatmap and filter ...
let parent = [{
id: 1,
value: "ABC",
},
{
id: 2,
value: "DEF",
},
{
id: 3,
value: "GHI",
},
{
id: 4,
value: "JKL",
},
{
id: 5,
value: "MNO",
},
{
id: 6,
value: "PQR",
},
]
let child = [{
childid: 1,
value: "ABC",
},
{
childid: 2,
value: "DEF",
},
{
childid: 10,
value: "GHI",
},
]
const res = parent.flatMap(x => child.filter(y => y.childid === x.id))
console.log(res)
This would work
parent.filter(p => child.some(c => c.childid === p.id))
Wat happens is
For each element in parent array, find the corresponding element in the child array
If it exists the filter will see it as truthy and keep the parent element, if not it will be falsy and filter wil discard it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
const filterResult = parent.filter(x => child.some(y => y.childid == x.id))
You can use a reduce function along with a forEach to loop through the child elements and compare against the parent.
const result = parents.reduce((acc, parent) => {
children.forEach((child) => {
if (parent.id === child.childid) {
acc.push(parent);
}
});
return acc;
}, []);
console.log(result); // [{"id":1,"value":"ABC"},{"id":2,"value":"DEF"}]
const parents = [{
id: 1,
value: 'ABC',
},
{
id: 2,
value: 'DEF',
},
{
id: 3,
value: 'GHI',
},
{
id: 4,
value: 'JKL',
},
{
id: 5,
value: 'MNO',
},
{
id: 6,
value: 'PQR',
},
];
const children = [{
childid: 1,
value: 'ABC',
},
{
childid: 2,
value: 'DEF',
},
{
childid: 10,
value: 'GHI',
},
];
const result = parents.reduce((acc, parent) => {
children.forEach((child) => {
if (parent.id === child.childid) {
acc.push(parent);
}
return acc;
});
return acc;
}, []);
console.log(result);
MDN Reduce

nested for loops to get another object-array output

I need to multiply all the "values" inside "obj1" with the "percent' inside obj2 based on the id of each object. What would be the best way to do that? I've tried with for loop and reduce but I wasn't successful. Any help will be appreciated.
const obj1 = [ { id: 1, value: 10 }, { id: 2, value: 10 } ]
const obj2 = {
len: {
id: 1,
nj: "321345",
percent: 0.05,
},
wor: {
id: 2,
nj: "321345",
percent: 0.1,
}
}
outputExpected: [ { id: 1, value: 0.5 }, { id: 2, value: 1 } ]
You can do that by going through and matching the ids. there are some optimizations that can be made if they are sorted however.
const obj1 = [ { id: 1, value: 10 }, { id: 2, value: 10 } ]
const obj2 = {
len: {
id: 1,
nj: "321345",
percent: 0.05,
},
wor: {
id: 2,
nj: "321345",
percent: 0.1,
}
}
const x = Object.keys(obj2).map((key,index)=>{
const { id, value } = obj1.find(({id})=>id===obj2[key].id)
return ({id,value:value*obj2[key].percent})
})
console.log(x)
//outputExpected: [ { id: 1, value: 0.5 }, { id: 2, value: 1 } ]
You can first create a lookup map using Map, then loop over the obj1 using map to get the desired result
const obj1 = [
{ id: 1, value: 10 },
{ id: 2, value: 10 },
];
const obj2 = {
len: {
id: 1,
nj: "321345",
percent: 0.05,
},
wor: {
id: 2,
nj: "321345",
percent: 0.1,
},
};
const map = new Map();
Object.values(obj2).forEach((v) => map.set(v.id, v));
const result = obj1.map((o) => ({ ...o, value: o.value * map.get(o.id).percent }));
console.log(result);
This should work for you but doesnt handle exeptions if the id doesnt exist in both objects.
// First get the values in an array for easier manipulation
const aux = Object.values(obj2)
const output = obj1.map(ob => {
// Find the id in the other array.
const obj2Ob = aux.find(o => o.id === ob.id) // The id must exist in this aproach
return {
id: ob.id,
value: ob.value * obj2Ob.percent
}
})
console.log(output) // [ { id: 1, value: 0.5 }, { id: 2, value: 1 } ]

How to modify the object and convert to array of objects javascript

How to change object to array of objects in javascript.
How to modify object and get the new aray of objects in javascript
Expected Result should be as input object weeks x 2 times (4 objects in output array)
for each item.
In Expected Output,
group key represents the weeks columns array,
should create a arraylist of each item desc, and interval qty per week
function createObject(obj){
const results = [];
for (var itm of obj.items) {
group: Object.values(obj.options).map((opt, index)=>opt.start+"-"+opt.end)
}
}
var obj = {
options: {
w1: {start:"Jan",end: "1"},
w2: {start:"Feb", end: "1"}
},
intervals: {
t1: {begin: "1", end: "2", totalqty: 2,totalamt: 200},
t2: {begin: "4", end: "7", totalqty: 3, totalamt: 300},
}
items: [
{
name: "s1",
desc: "sample1",
w1: {t1: {qty:0},t2: {qty:1}},
w2: {t1: {qty:1},t2: {qty:2}}
}
{
name: "s2",
desc: "sample2",
w1: {t1: {qty:0},t2: {qty:0}},
w2: {t1: {qty:0},t2: {qty:1}}
}
]
}
Expected Output:
[
{
group:"Jan 1", // represents w1
columns: [
{
col: 'desc',
value: 'sample1' // item.desc
},
{
col: '1-2', // represents t1
value: 0 , // represents t1.qty
},
{
col: '4-7', // represents t2
value: 1 // represents w1.t2.qty
}
]
},
{
group:"Feb 1", // represents w2
columns: [
{
col: 'desc',
value:'sample1'
},
{
col: '1-2', // represents t1
value:1 , // represents t1.qty
},
{
col: '4-7', // represents t2
value:2 ,// represents t2.qty
}
]
},
{
group:"Jan 1",
columns: [
{
col: 'desc',
value:'sample2'
},
{
col: '1-2',
value:0,
},
{
col: '4-7',
value:0
}
]
},
{
group:"Feb 1",
columns: [
{
col: 'desc',
value:'sample2'
},
{
col: '1-2',
value:0 ,
},
{
col: '4-7',
value:1,
}
]
}
]
Please try the below code. It produces the expected result
function createObject(obj){
return obj.items.map((item) => {
return Object.keys(obj.options).map((optKey) => {
const option = obj.options[optKey];
const items = {
'group' : `${option.start} ${option.end}`,
'columns': [{col: 'desc', value: item.desc}]
};
const intervals = item[optKey];
Object.keys(intervals).forEach((interval) => {
items.columns.push({
col: `${obj.intervals[interval].begin}-${obj.intervals[interval].end}`,
value: intervals[interval].qty
})
})
return items;
})
});
}

How to convert json to tree array in JS?

I would like to convert this json / object to this specific structure below to allow me to use a treeList component.
I've tried to build a recursive function but I didn't find the solution yet.
Thanks for your help
const data = {
parent1: {
child1: { bar: "1" },
child2: "2"
},
parent2: {
child1: "1"
}
}
to
const treeData = [
{
title: "parent1",
key: "parent1",
children: [
{
title: "child1",
key: "child1",
children: [{ title: "bar", key: "bar", value: "1" }]
},
{
title: "child2",
key: "child2",
value: "2"
}
],
},
{
title: "parent2",
key: "parent2",
children: [
{
title: "child1",
key: "child1",
value: "1"
}
]
}
]
You could take an iterative and recursive approach.
function getNodes(object) {
return Object
.entries(object)
.map(([key, value]) => value && typeof value === 'object'
? { title: key, key, children: getNodes(value) }
: { title: key, key, value }
);
}
const data = { parent1: { child1: { bar: "1" }, child2: "2" }, parent2: { child1: "1" } },
result = getNodes(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
just share sample, a little different from yours. But it give you a hint with recursive function.
https://jsfiddle.net/segansoft/7bdxmys4/1/
function getNestedChildren(arr, parent) {
var out = []
for (var i in arr) {
if (arr[i].parent == parent) {
var children = getNestedChildren(arr, arr[i].id)
if (children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
var flat = [{
id: 1,
title: 'hello',
parent: 0
},
{
id: 2,
title: 'hello',
parent: 0
},
{
id: 3,
title: 'hello',
parent: 1
},
{
id: 4,
title: 'hello',
parent: 3
},
{
id: 5,
title: 'hello',
parent: 4
},
{
id: 6,
title: 'hello',
parent: 4
},
{
id: 7,
title: 'hello',
parent: 3
},
{
id: 8,
title: 'hello',
parent: 2
}
]
var nested = getNestedChildren(flat, 0)
document.write('<pre>' + JSON.stringify(nested, 0, 4) + '</pre>');

Categories

Resources