按值数组过滤对象数组中的嵌套数组

时间:2018-08-02 09:43:55

标签: javascript arrays object filter lodash

考虑下面的对象数组:

[
    {
        "guid": "j5Dc9Z",            
        "courses": [
            {
                "id": 1,
                "name": "foo",                    
            }
        ]
    },
    {
        "guid": "a5gdfS",
        "courses": [
            {
                "id": 2,
                "name": "bar",                    
            },
            {
                "id": 3,
                "name": "foo",                    
            },    
        ]
     },
     {
        "guid": "jHab6i",
        "courses": [
            {
                "id": 4,
                "name": "foobar",                    
            }   
        ]
     },  
     {...}    
]

我正在尝试过滤对象数组,将嵌套courses数组中的ID与以下数组中的ID进行比较:

filter.courses = [1,3]

以下行适用于数组中的第n个值:(通过https://stackoverflow.com/a/41347441/9766768

let fil = filter(this.results, { courses: [{ id: this.filter.courses[n] }]});

但是,我希望做到这一点(下面的伪代码):

let fil = filter(this.results, { courses: [{ id: this.filter.courses }]});

预期的输出将是包含任何课程ID元素的对象数组,在这种情况下:

[
    {
        "guid": "j5Dc9Z",            
        "courses": [
            {
                "id": 1,
                "name": "foo",                    
            }
        ]
    },
    {
        "guid": "a5gdfS",
        "courses": [
            {
                "id": 2,
                "name": "bar",                    
            },
            {
                "id": 3,
                "name": "foo",                    
            },    
        ]
     }   
]

在这种情况下,什么是最佳解决方案?避免循环将是一个好处。

3 个答案:

答案 0 :(得分:3)

如果您试图过滤课程ID包含在filter.courses中的元素,则可以使用Array#everyArray#includes来做到这一点:

const data = [{"guid":"j5Dc9Z","courses":[{"id":3,"name":"foo"}]},{"guid":"a5gdfS","courses":[{"id":1,"name":"bar"},{"id":3,"name":"foo"}]},{"guid":"jHab6i","courses":[{"id":7,"name":"foobar"}]}];
const courses = [1, 6, 3];

const r = data.filter(d => d.courses.every(c => courses.includes(c.id)));
console.log(r);

答案 1 :(得分:0)

尝试一下

results = [
        {
            "guid": "j5Dc9Z",            
            "courses": [
                {
                    "id": 3,
                    "name": "foo",                    
                }
            ]
        },
        {
            "guid": "a5gdfS",
            "courses": [
                {
                    "id": 1,
                    "name": "bar",                    
                },
                {
                    "id": 3,
                    "name": "foo",                    
                },    
            ]
         } 
    ]

var filter = [1]
console.log(results.map(result=>{
      result.courses = result.courses.filter(course=>(filter.includes(course.id)))
      return result
    }))

答案 2 :(得分:0)

在那里探索我的递归解决方案:Playground Link

使用此解决方案可以将嵌套的对象数组从顶层逐层过滤到底层。