我想在JavaScript多层次的数组对象进行搜索。
[{ “头”: “标题1”, “列表”:[{ “名称”: “名称1”, “降序”: “递减1”},{ “名称”: “名称1”, “降序”: “DESC 1”}]},{ “头”: “标题2”, “列表”:[{ “名称”: “名称1”, “降序”: “递减1”},{ “名称”:“名称1" , “降序”: “递减1”}]}]
如果我们搜索“标题2”
预期结果 :
[{ “头”: “标题2”, “列表”:[{ “名称”: “名称1”, “降序”: “递减1”},{ “名称”: “名称1”, “降序”: “DESC 1”}]}]
如果我们搜索“名称1”
预期结果 :
[{ “头”: “标题1”, “列表”:[{ “名称”: “名称1”, “降序”: “递减1”},{ “名称”: “名称1”, “降序”: “DESC 1”}]},{ “头”: “标题2”, “列表”:[{ “名称”: “名称1”, “降序”: “递减1”},{ “名称”:“名称1" , “降序”: “递减1”}]}]
寻找一个优化的方式来做到这一点的搜索。谁能帮我解决这个问题?
更新:无效的JSON格式
你可以采取给定对象的嵌套值的所需值的递归搜索。
function filter(array, value) {
function find(object) {
return Object
.values(object)
.some(v => v === value || v && typeof v === 'object' && find(v));
}
return array.filter(find);
}
var array = [{ head: "Heading 1", list: [{ name: "name 1", desc: "desc 1" }, { name: "name 1", desc: "desc 1" }] }, { head: "Heading 2", list: [{ name: "name 1", desc: "desc 1" }, { name: "name 1", desc: "desc 1" }] }]
console.log(filter(array, "Heading 2"));
console.log(filter(array, "name 1"));
.as-console-wrapper { max-height: 100% !important; top: 0; }