Home > front end >  How to loop into the array that coming from a filter array?
How to loop into the array that coming from a filter array?

Time:02-17

Question, I have objects that I want to filter to get a specific value, but the problem is I need to map also a specific key to get all the value that need for my filter.

Sample code

const arr = [{
    "invitedPeopleId": [
        {
            "isAdmin": false,
            "isActive": true,
            "_id": "6127a0d12a55f41b380482c3",
        }
    ],
    "_id": "620be40739797c2064d9e26f",
    "projectId": {
        "_id": "620914a24d35c13d48c6be2a"
    },
    "taskCreatorId": {
        "isAdmin": true,
        "isActive": true,
        "_id": "6127a0bb2a55f41b380482c0"
    },
    "taskName": "Create login page for user registration"
}]
    
const compare = '6127a0d12a55f41b380482c3';
    
arr.filter((x) => x.contact.map((y) => y.landline) === compare); // return empty

Thanks!

CodePudding user response:

You could filter by taking contact and ther if some value compares with the wanted one.

const
    array = [{ _id: 1234, name: 'john', contact: [{ landline: '321321' }, { mobile: '123131' }] }, { _id: 1234, name: 'jane', contact: [{ landline: '5435353' }, { mobile: '5435353' }] }],
    compare = '321321',
    result = array.filter(({ contact }) =>
        contact.some(({ landline }) => landline === compare)
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related