【问题标题】:How to filter array of objects with nested arrays based on other arrays如何根据其他数组过滤具有嵌套数组的对象数组
【发布时间】:2020-10-17 14:29:21
【问题描述】:

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

示例代码。

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"];

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

我已尝试使用过滤器、包含,但没有运气查看类似问题的许多其他答案。

非常感谢。

【问题讨论】:

  • .filter 两次调用.every,如sizeArray.every(s => obj.size.includes(s)) && (the same for tagArray)

标签: javascript arrays filtering


【解决方案1】:

我猜这可能是你需要的:

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);

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 2021-03-21
    • 2021-08-22
    • 2020-03-11
    • 2013-10-08
    • 2019-05-22
    • 2022-12-07
    • 2020-07-18
    • 2019-07-09
    相关资源
    最近更新 更多