Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

javascript - Filter nested array in object array by array of values

Considering below object array:

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

I am trying to filter an object array, comparing IDs in the nested courses array with in the below array:

filter.courses = [1,3]

The following line works for the nth value in the array: (via https://stackoverflow.com/a/41347441/9766768)

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

However, I'm hoping to achieve this (pseudo code below):

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

Expected output would be an array of objects containing any of the course IDs elements, in this case:

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

What would be considered the best solution in this case? Avoiding loops would be a bonus.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're trying to filter the elements whose course IDs contain in the filter.courses, you may use Array#every and Array#includes to do that:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...