1

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!

7
  • If contact was an object (not an array) with landline and mobile properties your data would be easier to navigate. Commented Feb 16, 2022 at 15:02
  • "return empty" - Because you strictly compare an array against a string. Commented Feb 16, 2022 at 15:05
  • What is the expected output/result? Why .filter()? Commented Feb 16, 2022 at 15:06
  • Please try to either change compare as 321321 (and not '321321') - OR - change landline: 321321 to landline: '321321'. Because 321321 === '321321' may be false (the left-side is a number; whereas right-side is a string). Okay, the question is updated now. Commented Feb 16, 2022 at 15:20
  • Yeah, I know it will return empty, I forgot to add ''. But the arr is just a sample array. Commented Feb 16, 2022 at 15:21

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.