Home > Net >  array of strings to tree data structure?
array of strings to tree data structure?

Time:01-13

There is data returned from server containing an array of strings as hierarchy like this:

var array = [
 "house.bedroom.bed",
 "house.kitchen.spoon",
 "house.kitchen.knife",
 "house.bedroom.sofa",
 "house.bedroom.tv",
 "plants.trees",
 "house.birds.parrot.grey"
 ]

i have successful made a tree data structure as object out of it to make Output the data in tree form below:

  house
    bedroom
      bed
      sofa
      tv
    kitchen
      spoon
      knife
    birds
      parrot
        grey
  plants
    trees

and is there any way to pick a string? for example of asked "kitchen" i want to return all related to that string like this:

house.kitchen.knife
house.kitchen.spoon

Here the codes that i learned:

function find([key, values], string, temp = []) {
    var result;
    temp = temp.concat(key);
    if (key === string) {
        return temp.slice(1).join('.');
    }
    values.some(a => result = find(a, string, temp));
    return result;
}


var result = array.reduce((r, s) => {
        ('root.'   s).split('.').reduce((a, item) => {
            var array = a.find(([v]) => v === item);
            if (!array) {
                a.push(array = [item, []]);
            }
            return array[1];
        }, r);
        return r;
    }, []).pop();

console.log(find(result, 'kitchen'));
console.log(result);

my output is:

house.kitchen

CodePudding user response:

I propose to filter the original array

const data = ["house.bedroom.bed","house.kitchen.spoon", "house.kitchen.knife","house.bedroom.sofa","house.bedroom.tv",
 "plants.trees","house.birds.parrot.grey"];
 
 
 const result = data.filter((path) => path.split('.').includes('kitchen'));
 
 console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

CodePudding user response:

I believe I understand what you're asking. I would solve this problem with recursion.

function parse(items) {
   return items.reduce((acc, item) => {
      const k = item.slice(0, item.indexOf('.'))
      const v = item.slice(item.indexOf('.')   1).split('.')
      
      const newItem = {
        [k]: v.length > 1 ? parse(v) : v
      }

      return Object.assign(acc, newItem)
   }, { })
}

This is not a complete solution but should get the general idea across. For each item in the array, split it off into a key and a value. The key will be the string before the first ., and the value with either be the single string after that ., or an object containing children.

  •  Tags:  
  • Related