树的字符串路径Javascript

如何解决树的字符串路径Javascript

我有一个字符串格式的路径数组,如下所示:

[
  { _id: 'women/clothes/tops',count: 10 },{ _id: 'women/clothes/suits',count: 5 },{ _id: 'women/accessories',count: 2 },{ _id: 'men/clothes',count: 1 },]

我想将它们组合成这样的树结构:

[
  {
    _id: 'women',count: 17,children: [
      {
        _id: 'clothes',count: 15,children: [
          { _id: 'tops',{ _id: 'suits',count: 5 }
        ]
      },{
        _id: 'accessories',count: 2
      }
    ]
  },{
    _id: 'men',count: 1,count: 1
      }
    ]
  }
]

我想像一个递归函数调用一个reduce方法。但我无法弄清楚究竟如何。我有点受不了了。 非常感谢,如果有人已经这样做了并且有解决方案:)

编辑:

我不知道为什么这个问题被否决了,但我设法接近了这个解决方案。但是我仍然得到一个空的对象键,并且当没有孩子时我无法设法没有 children 键:


const getTree = (array) => {
  return array.reduce((a,b) => {
    const items = b._id.replace('\/','').split('/')
    return construct(a,b.count,items)
  },{})
}

const construct = (a,count,items) => {
  const key = items.shift()

  if(!a[key]) {
    a[key] = {
      _id: key,count: count,children: []
    }
    a[key].children = items.length > 0 ? construct(a[key].children,items) : null
  }
  else {
    a[key].count += count
    a[key].children = items.length > 0 ? construct(a[key].children,items) : null
  }
  return a
}

解决方法

这样的事情应该有效吗?

我首先创建了一个对象树,然后将其转换为具有子结构的对象数组。

注意:我在中间结构中的每个对象上使用了 _count 属性,以便稍后在循环键时(创建最终结构时),我可以忽略 _id 和 {{1 }} 很容易,并且只循环不以 _count 开头的“真正的孩子”键。

如果有任何不清楚的地方,请告诉我。

在写这篇文章之前我没有看你目前的尝试/解决方案,所以我的看起来很不一样。

_
const origData = [
  { _id: 'women/clothes/tops',count: 10 },{ _id: 'women/clothes/suits',count: 5 },{ _id: 'women/accessories',count: 2 },{ _id: 'men/clothes',count: 1 },];


const newObj = {};
for (let obj of origData) {
  //console.log(obj)
  const tempArr = obj._id.split('/');
  let tempHead = newObj; // pointer
  for (let idx in tempArr) {
    let head = tempArr[idx];
    if (!tempHead.hasOwnProperty(head)) {
      tempHead[head] = {};
    }
    tempHead = tempHead[head];
    tempHead._id = head;
    const currCount = tempHead._count || 0;
    tempHead._count = currCount + obj.count;
  }
  tempHead._count = obj.count;
}

console.log(newObj);
const finalArr = [];
let tempArrHead = finalArr; // pointer
let tempObjHead = newObj; // pointer

function recursiveStuff(currObj,currArr,copyObj) {
  let hasChildren = false;
  const keys = Object.keys(currObj).filter(a => !a.startsWith("_"));
  for (let key of keys) {
      hasChildren = true;
      const obj = {
        _id: currObj[key]._id,count: currObj[key]._count || 0,children: [],};
      currArr.push(obj);
      recursiveStuff(currObj[key],obj.children,obj)
  }
  if (hasChildren == false) {
    // console.log(copyObj);
    // there might be a more elegant way,but this works:
    delete copyObj.children;
  }
}

recursiveStuff(tempObjHead,tempArrHead)
console.log(finalArr);

中间结构:

.as-console-wrapper{
  max-height: 100% !important;
}

最终结构:

{
  "women": {
    "_id": "women","_count": 17,"clothes": {
      "_id": "clothes","_count": 15,"tops": {
        "_id": "tops","_count": 10
      },"suits": {
        "_id": "suits","_count": 5
      }
    },"accessories": {
      "_id": "accessories","_count": 2
    }
  },"men": {
    "_id": "men","_count": 1,"_count": 1
    }
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?