0

Looking for help, to generate a nested object tree from a string.

Example 1

A > B > C

Should result in object:

{
 name: A,
 children: [{
  name: B,
  children: [{
   name: C
  }],
 }]
}

Example 2

A > B > C | A > D > E

Result in object:

{
 name: A,
 children: [{
  name: B,
  children: [{
   name: C
  },{
   name: D,
   children: [{
    name: E
   }],
  }],
 }]
}

What I have so far:

Problem is, I am not sure how to properly solve the nesting.

let categoryTree = {
  categories: [{}]
}

const split = (string, seperator = '|', splitter = ' > ') => {
  if (!string.includes(seperator)) {
    let results = string.split(splitter)

    for (let i = 0; i < results.length; i++) {
      let lastNode = 0
      if (i != 0) {
        lastNode = i - 1
      }
      makeTree(results[i], results[lastNode], i)
    }

  }
  console.log(categoryTree)
  return categoryTree
}

const makeTree = (item, parent, i) => {
  if (categoryTree.categories[parent].name === item && categoryTree.categories[parent].name) {
    console.log('IN')
    categoryTree.categories[parent].categories.push({
      name: item,
      categories: [{}]
    })
  } else {
    categoryTree.categories.push({name: item, categories: []})
  }
}
5
  • You're asking for the code to do this? Commented Feb 23, 2017 at 16:42
  • 3
    What have you done so far? Commented Feb 23, 2017 at 16:42
  • We need to see your code so far so that we can help you solve your problem Commented Feb 23, 2017 at 16:44
  • What would be result for A > B > C | A > B > E Commented Feb 23, 2017 at 16:52
  • @NenadVracar A would have 1 children B. And B would have 2 children, C and E Commented Feb 23, 2017 at 16:55

1 Answer 1

3

You could use an iterative and recursive approach with an object as reference to the items.

var result = [],
    string = 'A > B > C | A > D > E';

string.split(' | ').forEach(function (a) {
    var keys = a.split(' > '),
        last = keys.pop();
    
    keys.reduce(function (r, k) {
        if (!r[k]) {
            r[k] = { _: [] };
            r._.push({ name: k, children: r[k]._ });
        }
        return r[k];
    }, this)._.push({ name: last });
}, { _: result });

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.