简体   繁体   中英

Filtering nested objects

I am trying to filter the list based on a particular roleType in a roles array, which is a array of objects.

Below is my json

this.rolesData =  [{
         "firstName": "Francis",
         "lastName": "Underwood",
         "middleName": "",
         "title": { "titleId": "1", "titleName": "AA" },
         "roles": [
             {"roleGuid" : 1,  "roleType" : 1 },  
             { "roleGuid" : 2,  "roleType" : 3 }
        ]
    },
    {
        "firstName": "Claire",
        "lastName": "Underwood",
        "middleName": "",
        "title": { "titleId": "2", "titleName": "BB" },
        "roles": [
            {"roleGuid" : 1,  "roleType" : 2 },  
            { "roleGuid" : 2,  "roleType" : 3 }, 
            { "roleGuid" : 3, "roleType" : 4 }
        ]
    }
];

I am trying to get the items that has roleType 1 in it. so for my example, it should return only first object as only first object has roleType 1 in its roles list.

I tried below, but it didn't work

this.rolesData.filter(data => {
    data.roles.filter(role => {
        if (role.roleType == 1) {
          return role;
        }
    });
});

.filter should take a function that will return true or false for a given item.

const results = this.rolesData.filter(data => {
    // Filter to matching roles
    const matchingRoles = data.roles.filter(role => {
        return role.roleType == 1;
    });
    // Return true if matching roles are found
    return matchingRoles && matchingRoles.length > 0;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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