Skip to content Skip to sidebar Skip to footer

Tree From Array Of Dot-separated Strings

I have an array of dot delimited strings which looks like the following data = [ 'Europe.UK.London.TrafalgarSq', 'Europe.UK.London.HydePark', 'Europe.UK.London.Oxford

Solution 1:

You could use a mapper object which has partial paths (or label) as key and a reference to the object in the tree as it's value. split the path at . and reduce the array with tree as the initialValue. If the path doesn't exist yet, add it to mapper and tree. Return the nested object in each iteration.

const data = ["Europe.UK.London.TrafalgarSq","Europe.UK.London.HydePark","Europe.UK.London.OxfordStreet","Europe.UK.London.City.Bank","Europe.France.Paris","Europe.France.Bordeaux"],
    mapper = {},
    tree = {
      label: 'Places',
      selectAllCheckbox: 'Un/select all',
      children: []
    }

for (const str of data) {
  let splits = str.split('.'),
      label = '';

  splits.reduce((parent, place) => {
    if (label)
      label += `.${place}`else
      label = place

    if (!mapper[label]) {
      const o = { label };
      mapper[label] = o;
      parent.selectAllCheckbox = true
      parent.children = parent.children || [];
      parent.children.push(o)
    }

    return mapper[label];
  }, tree)
}

console.log(tree)

Solution 2:

You could an iterative approach with a reduceing of the nested objects.

var data = ['Europe.UK.London.TrafalgarSq', 'Europe.UK.London.HydePark', 'Europe.UK.London.OxfordStreet', 'Europe.UK.London.City.Bank', 'Europe.France.Paris', 'Europe.France.Bordeaux'],
    children = data.reduce((r, s) => {
        s.split('.').reduce((q, _, i, a) => {
            q.selectAllCheckbox = true;
            var label = a.slice(0, i + 1).join('.'),
                temp = (q.children = q.children || []).find(o => o.label === label);
            if (!temp) q.children.push(temp = { label });
            return temp;
        }, r);
        return r;
    }, { children: [] }).children,
    tree = { label: 'Places', selectAllCheckbox: 'Un/select all', children };

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

Post a Comment for "Tree From Array Of Dot-separated Strings"