JavaScript 数组对象多级搜索值

JavaScript Array Object Multi Level Search Value

我想在 JavaScript 多级数组对象中搜索。

[{ "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" }] }]

如果我们搜索 "Heading 2"

预期结果:

[{ "head": "Heading 2", "list":[{ "name": "name 1", "desc": "desc 1" },{ "name": "name 1", "desc": "desc 1" }] }]

如果我们搜索 "name 1"

预期结果:

[{ "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" }] }]

正在寻找一种优化的方式来执行此搜索。谁能帮我解决这个问题?

已更新:无效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; }