i'd like to make a tree of objects from arrays. A nice solution has been provided to me (where i've discovered "reduce" method) here : Javascript build a tree from a string with object.create() Actually, my need is a bit different, and i don't manage to adapt the provided code... so I come back here to be helped !!! (thank you). I'll post the full initial code at the end of this post
input :
[
{
"name": "John Doe",
"service": "EE",
},
{
"name": "Jane Doe",
"service": "EE.EA",
},
{
"name": "Jack Smith",
"service": "EE.EA.EB",
},
{
"name": "Jill Smith",
"service": "EE.EA.EC"
},
{
"name": "Jake Smith",
"serviceLevel": "EE.EA.EC"
}
]
output:
{
"EE":
{
"serviceFather": "root",
"people": [
{
"name": "John Doe"
}],
"serviceChildren":
{
"EA":
{
"serviceFather": "EE",
"people": [
{
"name": "Jane Doe"
}],
"serviceChildren":
{
"EB":
{
"serviceFather": "EA",
"people": [
{
"name": "Jack Smith"
}],
"serviceChildren":
{}
},
"EC":
{
"serviceFather": "EA",
"people": [
{
"name": "Jill Smith"
},
{
"name": "Jake Smith"
}],
"serviceChildren":
{}
}
}
}
}
}
}
The initial code :
function format(data) {
const res = []
data.forEach(obj => {
obj.serviceTree.split('.').reduce((r, e, i, a) => {
console.log(r, e, i, a);
const oParent = r.find(({ name }) => name == a[i - 1]);
const match = r.find(({ name }) => name == e);
if (!match) {
const o = Object.create(service);
o.name = e;
if (!a[i + 1]) {
o.serviceName = obj.serviceName;
o.serviceTree = obj.serviceTree;
o.serviceLevel = i;
o.serviceParent = (i == 0 ? 'root' : a[i - 1]);
o.people = [{
familyName: obj.familyName,
firstName: obj.firstName,
jobTitle: obj.jobTitle,
rank: obj.rank,
phone: obj.phone,
mobile: obj.mobile,
mail: obj.mail
}];
if (oParent) {
oParent.serviceChildren.push(o);
} else {
o.serviceChildren = [];
r.push(o);
}
} else {
let treeStamp = a.slice();
treeStamp.pop();
o.serviceName = e;
o.serviceTree = treeStamp.join('.');
o.serviceLevel = i;
o.serviceParent = (i == 0 ? 'root' : a[i - 1]);
o.serviceChildren = [];
r.push(o);
}
return r;
} else {
if (!a[i + 1]) match.people.push({
familyName: obj.familyName,
firstName: obj.firstName,
jobTitle: obj.jobTitle,
rank: obj.rank,
phone: obj.phone,
mobile: obj.mobile,
mail: obj.mail
});
return match.serviceChildren;
}
}, res);
});
return res;
}