gpt4 book ai didi

javascript - 深度过滤对象的动态数组(通过字符串属性)

转载 作者:行者123 更新时间:2023-11-28 03:28:25 25 4
gpt4 key购买 nike

我想通过属性“name”过滤动态数组。
该数组有 3 种对象:“link”、“folder”和“app”。

{
type: "link",
name: ""
},
{
type: "folder",
name: "",
childs: []
},
{
type: "app",
name: "",
childs: []
}
  • 应用只能有链接作为子项。
  • 文件夹可以将所有 3 种类型(链接、文件夹、应用程序)作为子项。

如果子项与搜索值匹配,则其所有父项都会存活。(如果它们不匹配,它的 sibling 就会被过滤掉)

<小时/>

我有一个类似这样的数组:

var items = [
{
type: 'app',
name: 'bar',
childs: [
{
type: 'link',
name: 'mee'
}
]
},
{
type: 'folder',
name: 'fizz',
childs: [
{
type: 'link',
name: 'buzz'
},
{
type: 'app',
name: 'boo',
childs: []
}
]
},
{
type: 'folder',
name: 'bla',
childs: [
{
type: 'app',
name: 'blee',
childs: [
{
type: 'link',
name: 'blee'
},
{
type: 'link',
name: 'bar'
}
]
},
{
type: 'folder',
name: 'mee',
childs: [
{
type: 'app',
name: 'bar',
childs: [
{
type: 'link',
name: 'maa'
}
]
},
{
type: 'link',
name: 'mee'
}
]
}
]
},
{
type: 'link',
name: 'foo',
childs: [
{
type: 'folder',
name: 'baf',
childs: []
}
]
}
];
<小时/>

我设法编写了一个非深度过滤:
https://jsfiddle.net/6ocd5u8y
(我也希望对此代码有任何建议)

我还发现了深度过滤的代码,但使匹配子项的 sibling 保持事件状态并按任何字符串进行过滤:
https://jsfiddle.net/ndfu8cpL

<小时/>

像“bar”这样的搜索结果应该是:

filteredArray = [
{
type: 'app',
name: 'bar',
childs: []
},
{
type: 'folder',
name: 'bla',
childs: [
{
type: 'app',
name: 'blee',
childs: [
{
type: 'link',
name: 'bar'
}
]
},
{
type: 'folder',
name: 'mee',
childs: [
{
type: 'app',
name: 'bar',
childs: []
}
]
}
]
}
]
<小时/>

如果有人能帮助我,我将非常感激。

最佳答案

如果找到想要的属性或者嵌套数组在过滤后有一些项目,您可以构建新对象。

function filter(array, name) {
return array.reduce((r, o) => {
var childs = filter(o.childs || [], name);
if (o.name === name || childs.length) r.push(Object.assign({}, o, { childs }));
return r;
}, []);
}

var items = [{ type: 'app', name: 'bar', childs: [{ type: 'link', name: 'mee' }] }, { type: 'folder', name: 'fizz', childs: [{ type: 'link', name: 'buzz' }, { type: 'app', name: 'boo', childs: [] }] }, { type: 'folder', name: 'bla', childs: [{ type: 'app', name: 'blee', childs: [{ type: 'link', name: 'blee' }, { type: 'link', name: 'bar' }] }, { type: 'folder', name: 'mee', childs: [{ type: 'app', name: 'bar', childs: [{ type: 'link', name: 'maa' }] }, { type: 'link', name: 'mee' }] }] }, { type: 'link', name: 'foo', childs: [{ type: 'folder', name: 'baf', childs: [] }] }];

console.log(filter(items, 'bar'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 深度过滤对象的动态数组(通过字符串属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416613/

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