0

The first one is when we have an array holds regular elements like strings and I know how to use Includes on it.

But how about arrays holding objects as their element? How can I check if there is a certain value in those objects?

const arr = ['this', 'is', 'a test'];

console.log(arr.includes('this'));

const arr2 = [
  { id: '123', name: 'Alex' },
  { id: '345', name: 'Dan' },
  { id: '33', name: 'Joe' },
];

4
  • Use '.filter()' Commented Feb 16, 2022 at 14:34
  • 1
    What have you tried so far to solve this on your own? Commented Feb 16, 2022 at 14:35
  • @OnchoMeshkov Why that combination (especially .map())? Commented Feb 16, 2022 at 14:36
  • 1
    What is the use-case? What is the input? What property (a specific one, any) should be checked? What is the expected output? -> How do I ask a good question? Commented Feb 16, 2022 at 14:37

2 Answers 2

1

You can use the some function.

const arr2 = [
  { id: '123', name: 'Alex' },
  { id: '345', name: 'Dan' },
  { id: '33', name: 'Joe' },
];

console.log(arr2.some(item => item.name==="this" ))

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

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

Comments

1

if you want a returned array of values that match = >

 const filtered = arr2.filter((item)=>item.name == 'value')

if you want bool(true||false) =>

 const filtered = arr2.filter((item)=>item.name == 'value').length > 0

or using some as mentioned above.

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.