gpt4 book ai didi

javascript - 如何提取嵌套对象数组中 'enabled' 对象的路径

转载 作者:行者123 更新时间:2023-11-30 06:14:37 31 4
gpt4 key购买 nike

我是递归的新手,我有一个包含嵌套对象数组的 JSON 结构。其中一些对象启用了 bool 值:true。我正在尝试弄清楚如何提取所有已启用对象及其子对象的路径。

我尝试通过删除未使用的路径来清理原始对象,但我在访问父对象时迷路了。我还尝试使用点符号构建一个单独的路径数组,因为我可能可以从中构建一个新的嵌套对象。我对点符号提取的最新尝试:


const sourceData = {
title: "Work",
tags: [
{
title: "Cleaning",
tags: [
{
title: "Floors"
},
{ title: "Windows", enabled: true },
{ title: "Ceilings", enabled: true }
]
},
{
title: "Maintenance",
tags: [
{
title: "Walls",
enabled: true,
tags: [
{
title: "Brickwall"
},
{
title: "Wooden wall"
}
]
},
{
title: "Roof"
}
]
},
{
title: "Gardening"
}
]
};

function getEnabledPaths(level, acc) {
for (const tag of level.tags) {
if (tag.enabled) {
return tag.title;
} else if (tag.hasOwnProperty("tags")) {
var path = this.getEnabledPaths(tag);
if (path) acc.push(tag.title + "." + path);
}
}
return acc;
}

console.log(getEnabledPaths(sourceData, []));

我只得到:

    [
"Cleaning.Windows",
"Maintenance.Walls"
]

理想情况下我会得到这样的结果:

    [
'Work.Cleaning.Windows',
'Work.Cleaning.Ceilings',
'Work.Maintenance.Walls.Brickwall',
'Work.Maintenance.Walls.Wooden Wall'
]

在一个完美的世界中(但我尝试了好几天,然后回去获取点符号结果):


{
title: "Work",
tags: [
{
title: "Cleaning",
tags: [
{
title: "Windows",
enabled: true
},
{
title: "Ceilings",
enabled: true
}
]
},
{
title: "Maintenance",
tags: [
{
title: "Walls",
enabled: true,
tags: [
{
title: "Brickwall"
},
{
title: "Wooden wall"
}
]
}
]
}
]
};

最佳答案

递归函数的关键在于 a) 处理子项和 b) 项目本身。

这是我的看法,似乎可行:

const sourceData = {title:"Work",tags:[{title:"Cleaning",tags:[{title:"Floors"},{title:"Windows",enabled:true},{title:"Ceilings",enabled:true}]},{title:"Maintenance",tags:[{title:"Walls",enabled:true,tags:[{title:"Brickwall"},{title:"Woodenwall"}]},{title:"Roof"}]},{title:"Gardening"}]};

function itemFilter(item) {
// enabled? done with this item
if (item.enabled) return item;
// not enabled and no tags? set to null
if (!item.tags) return null;
// filter all children, remove null children
item.tags = item.tags.map(child => itemFilter(child)).filter(child => child);
return item;
}

console.log(itemFilter(sourceData));
.as-console-wrapper {
max-height: 100vh !important;
}

关于javascript - 如何提取嵌套对象数组中 'enabled' 对象的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56914198/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com