Skip to content Skip to sidebar Skip to footer

Javascript Build A Tree From A String With Object.create()

I'd like to create a tree of services from a string which are properties of people. I manage to do it, but the code is quite ugly, and it's a king of practice for me for the trick

Solution 1:

You could use split on service property and then forEach loop and reduce to iterate nested tree and add to array.

const 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" }
]

let service = {
  serviceFather: "",
  serviceChildren: [],
  people: [],
};

functioncreate(data) {
  const res = []
  data.forEach(obj => {
    obj.service.split('.').reduce((r, e, i, a) => {
      const match = r.find(({ name }) => name == e);
      if(!match) {
        const o = Object.create(service);
        o.name = e;
        o.serviceFather = (i == 0 ? 'root' : a[i - 1])
        o.people = [{ name: obj.name }]
        o.serviceChildren = [];
        r.push(o)
        return r;
      } else {
        if(!a[i + 1]) match.people.push({ name: obj.name })
        return match.serviceChildren
      }
    }, res)
  })
  return res;
}

const result = create(data)
console.log(result)

Solution 2:

You could take a dummy object and iterate the service levels.

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, a) => {
            var temp = (o.serviceChildren = o.serviceChildren || []).find(({ name }) => name === k);
            if (!temp) {
                o.serviceChildren.push(temp = {
                    name: k,
                    serviceFather: a[i - 1] || 'root',
                    people: []
                });
            }
            return temp;
        }, { serviceChildren: result })
        .people.push({ name });
});

console.log(result);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "Javascript Build A Tree From A String With Object.create()"