简体   繁体   English

如何基于其他 arrays 过滤具有嵌套 arrays 的对象数组

[英]How to filter array of objects with nested arrays based on other arrays

I have an array of objects.我有一个对象数组。 I want to filter to include only objects where all of the elements in the test arrays are present in the original array.我想过滤以仅包含测试 arrays 中的所有元素都存在于原始数组中的对象。

Sample code.示例代码。

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"],
    }

Test arrays测试 arrays

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

I want the filtered array to only include the second object.我希望过滤后的数组只包含第二个 object。

I've tried with filter, includes and no luck looking over many other answers to similar questions.我已经尝试过使用过滤器,包含并且没有运气查看类似问题的许多其他答案。

Thanks a lot.非常感谢。

I'm guessing this might be what you need:我猜这可能是你需要的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM