3

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;
}
CoStiC
  • 85
  • 8
  • If you weren't able to adapt the answes, the answrers made something wrong. – Jonas Wilms Apr 15 '19 at 21:20
  • yes, i ve changed a bit the provided code to make it working... but actually, it wasn’t the solution I was looking for at the end... – CoStiC Apr 15 '19 at 21:38

2 Answers2

2

You could take the part of splitted service and take this as key for accessing the nested objects.

var data = [{ 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", service: "EE.EA.EC" }],
    result = {};

data.forEach(({ name, service }) => {
    service
        .split('.')
        .reduce((o, k, i, { [i - 1]: serviceFather = 'root' }) => {
            o.serviceChildren = o.serviceChildren || {};
            o.serviceChildren[k] = o.serviceChildren[k] || { serviceFather, people: []  };
            return o.serviceChildren[k];
        }, { serviceChildren: result })
        .people.push({ name });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I'm trying to undestand '.reduce((o, k, i, { [i - 1]: serviceFather = 'root' })' : the last parameter isn't the array you're working on? I couldn't imagine that you could fill a parameter here...(?) – CoStiC Apr 15 '19 at 22:07
  • 1
    the right parameter is a destructuring by taking the array and it gets the element before the actual index and takes `'root'` as default value, if no item is available. – Nina Scholz Apr 16 '19 at 06:25
  • i just get it! it's [i - 1] OR serviceFather = 'root' – CoStiC Apr 16 '19 at 07:28
  • lol, you own this ^^ thank you so much. As i didn't know that it was possible i just forget the ternary writing... thank you again for all this. If i may ask another question : is it possible to initiate an object with all parameters, before calling that function, and push a value to 'serviceFather' parameter when you call the function?like : let myObj = {parameter1: "",parameter2:"",serviceFather:"root"...}, data=[...]; data.forEach(o,k,i, {[i - 1] : myObj.serviceParent = "root"} ? – CoStiC Apr 16 '19 at 07:38
  • it is not possible to assign a value where a [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) takes plaxe, but you can take a deeper destructuring (which does not work here, as i see it). maybe the comment section is not the right place for it. if necessary, you could ask a new question. btw, a [conditional (ternary) operator `?:`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) is not in the code above. the colon `:` is part of the destructuring. – Nina Scholz Apr 16 '19 at 07:50
1

The code given is overly complicated. It could be as easy as:

 const root = { name: "root", serviceChildren: {} };

 for(const { name, service } of input) {
    let acc = root;
    for(const key of service.split(".")) {
       if(!acc.serviceChildren[key]) {
         acc.serviceChildren[key] = {
           name: key,
           serviceFather: acc.name,
           serviceChildren: {},
           people: [],
        };
      }
     acc = acc.serviceChildren[key];
    }

    acc.people.push({ name });
 }

 const output = root.serviceChildren;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • you are definately right... I was so much trying to adapt the first code that I didn’t step backward to look for another solution... thank you! – CoStiC Apr 15 '19 at 21:46