如何解决树的字符串路径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 举报,一经查实,本站将立刻删除。