如何从JavaScript中的字符串中生成树



寻求帮助,从字符串生成嵌套对象树。

示例1

A > B > C

应导致对象:

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

示例2

A > B > C | A > D > E

结果对象:

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

我到目前为止拥有的内容:

问题是,我不确定如何正确解决嵌套。

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: []})
  }
}

您可以使用对象引用的迭代和递归方法。

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

相关内容

  • 没有找到相关文章