Skip to content Skip to sidebar Skip to footer

Create An Tree Of Objects From Arrays

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 ob

Solution 1:

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; }

Solution 2:

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;

Post a Comment for "Create An Tree Of Objects From Arrays"