We have some JSON data where each parent array object can have a property that is an array of "children" along the lines of the following :
data: [
{
value: 1,
parent_id: null,
label: "1.0 - TT One",
children: [
{
value: 3,
label: "1.1 - TT One-One",
parent_id: 1,
},
{
value: 4,
label: "1.2 - TT One-Two",
parent_id: 1,
}
]
},
{
value: 2,
parent_id: null,
label: "2.0 - TT Two",
children: [
{
value: 5,
label: "2.1 - TT Two-One",
parent_id: 2,
}
]
}
]
We'd like to "flatten" the children so that we end up with one array that is all the parents and children as follows (it does not have to stay named data if not efficient):
data: [
{
value: 1,
parent_id: null,
label: "1.0 - TT One"
},
{ <-- FORMER CHILD
value: 3,
label: "1.1 - TT One-One",
parent_id: 1
},
{ <-- FORMER CHILD
value: 4,
label: "1.2 - TT One-Two",
parent_id: 1,
},
{
value: 2,
parent_id: null,
label: "2.0 - TT Two"
},
{ <-- FORMER CHILD
value: 5,
label: "2.1 - TT Two-One",
parent_id: 2,
}
]
Thoughts on how best to accomplish this in an efficient manor? We have underscore if that will help.
Found a buttload of array to array flatten and some object to array flattens, but nothing combining the two. If we had this, we wouldn't have needed to post. If it's not obvious from exactly what we have to exactly what we need, what is the point?
the point is to understand what is your data structure and how to visit every element of that data structure.
Since there are only 2 levels you do not even need to find a general solution to transform your initial data into an array. Do you know how to traverse an array? then you know how to traverse an element that has an array as property as well.
Anyway here is both a recursive and a non recursive generalized solution.
var d = [{
value: 1,
parent_id: null,
label: "1.0 - TT One",
children: [{
value: 3,
label: "1.1 - TT One-One",
parent_id: 1,
},
{
value: 4,
label: "1.2 - TT One-Two",
parent_id: 1,
}
]
},
{
value: 2,
parent_id: null,
label: "2.0 - TT Two",
children: [{
value: 5,
label: "2.1 - TT Two-One",
parent_id: 2,
}]
}
];
function walkRecursive(data) {
let result = []
data.forEach(element => {
let e = { ...element}
result.push(e);
if (e.children) {
let children = walkRecursive(e.children)
result = result.concat(children)
delete e.children
}
});
return result;
}
function walk(data) {
data = data.slice()
let result = []
let d, oldData;
while (d = data.shift()) {
let el = { ...d}
result.push(el)
if (el.children) {
oldData = data
data = el.children.slice();
delete el.children;
} else {
if (oldData && data.length == 0) {
data = oldData
oldData = null;
}
}
}
return result;
}
console.log(walkRecursive(d))
console.log(walk(d))
https://codeburst.io/learn-and-understand-recursion-in-javascript-b588218e87ea
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments