如何基于其他数组使用嵌套数组过滤对象数组

时间:2020-06-26 23:05:46

标签: javascript arrays filtering

我有一个对象数组。我希望过滤以仅包含原始数组中存在测试数组中所有元素的对象。

示例代码。

const cards = [
    {
        id: "1",
        name: "J",
        tag: ["red", "yellow", "blue", "white"],
        size: ["small", "medium"],
    },
    {
        id: "2",
        name: "S",
        tag: ["red", "green", "black"],
        size: ["small", "medium"],
    },
    {
        id: "3",
        name: "K",
        tag: ["green", "purple", "brown", "white"],
        size: ["large"],
    }

测试数组

const sizeArray = ["medium", "small"];
const tagArray = ["red", "black"];

我希望过滤后的数组仅包含第二个对象。

我尝试使用过滤器,包括过滤器,也没有运气寻找类似问题的许多其他答案。

非常感谢。

1 个答案:

答案 0 :(得分:3)

我猜这可能是您需要的:

const cards = [
    {
        id: "1",
        name: "J",
        tag: ["red", "yellow", "blue", "white"],
        size: ["small", "medium"],
    },
    {
        id: "2",
        name: "S",
        tag: ["red", "green", "black"],
        size: ["small", "medium"],
    },
    {
        id: "3",
        name: "K",
        tag: ["green", "purple", "brown", "white"],
        size: ["large"],
    }
];

const sizeArray = ["medium", "small"];
const tagArray = ["red", "black"];
// filtering the cards array
const filltered = cards.filter(ch => {
    // according have every size in sizeArray and
    // every tag in tagsArray
    return sizeArray.every(size => ch.size.includes(size))
        && tagArray.every(tag => ch.tag.includes(tag));
});

console.log(filltered);