javascript - 如何使用字符串数组过滤嵌套对象

标签 javascript arrays vue.js search filtering

let products = [
    {
        name: "A",
        color: "Blue",
        size: {
            size1: 1,
            size2: 2,
            size3: 3,
        },
    },
    {
        name: "B",
        color: "Blue",
        size: {
            size1: 5,
            size2: 19,
            size3: 22,
        },
    },
    { name: "C", color: "Black", size: 70 },
    { name: "D", color: "Green", size: 50 },
];

filters = ['Blue','2']; 

结果必须是检查数组中所有字符串的对象

 {
    name: "A",
    color: "Blue",
    size: {
        size1: 1,
        size2: 2,
        size3: 3,
    },
},

无论其值(value)如何,研究都必须被接受

最佳答案

您可以通过以某种方式使用堆栈来解析嵌套,无论是通过递归还是显式迭代地使用堆栈。这是一个递归解决方案:

function getFiltered(obj, filters, found = null) {
    let outermostCall = (found === null);
    if (outermostCall) { //outermost call
        found = [];
        for (let index = 0; index < filters.length; index++) {
            found[index] = false;
        }
    }
    for (let key in obj) {
        if (typeof obj[key] === 'object') {
            let tempFound = getFiltered(obj[key], filters, found);
            for (let index = 0; index < found.length; index++) {
                if (tempFound[index]) found[index] = true;
            }
        } else {
            let foundIndex = -1;
            for (let index = 0; index < filters.length; index++) {
                if (filters[index] == obj[key]) {
                    foundIndex = index;
                    index = filters.length;
                }
            }
            if (foundIndex >= 0) {
                found[foundIndex] = true;
            }
        }
    }
    if (outermostCall) {
        return !found.filter(item => !item).length;
    }
    return found;
}

function getAllFiltered(array, filters) {
    let output = [];
    for (let obj of array) {
        if (getFiltered(obj, filters)) output.push(obj);
    }
    return output;
}

let products = [
    {
        name: "A",
        color: "Blue",
        size: {
            size1: 1,
            size2: 2,
            size3: 3,
        },
    },
    {
        name: "B",
        color: "Blue",
        size: {
            size1: 5,
            size2: 19,
            size3: 22,
        },
    },
    { name: "C", color: "Black", size: 70 },
    { name: "D", color: "Green", size: 50 },
];

let filters = ['Blue','2']; 

console.log(getAllFiltered(products, filters));

关于javascript - 如何使用字符串数组过滤嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74489636/

相关文章:

javascript - 返回此递归循环的累积字符串

javascript - 区分 JavaScript Set 和不可变 Set

java - 如何创建我自己的 Collection ?

java - 从数组中删除所有零

javascript - sessionStorage 中的存储 Vue.js 实例是可接受的范例吗?

javascript - 为什么要安装前端库?

javascript - underscore.js: _.zip.apply 示例

javascript - React onchange 事件 : this. setState() 未设置状态?

java - 查找出现最小值的数组索引

vue.js - v-html 不在 Vue 2 中呈现 vue 组件