Monday, June 3, 2024
42
rated 0 times [  43] [ 1]  / answers: 1 / hits: 19846  / 5 Years ago, tue, may 14, 2019, 12:00:00

let's say I have an array of objects:



let arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]


I need to check whether that array includes the name 'Jack' for example using:



if (arr.includes('Jack')) {
// don't add name to arr

} else {
// push name into the arr

}


but arr.includes('Jack') returns false, how can I check if an array of objects includes the name?


More From » ecmascript-6

 Answers
6

Since you need to check the object property value in the array, you can try with Array​.prototype​.some():




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






let arr = [
{
name: 'Jack',
id: 1
},
{
name: 'Gabriel',
id: 2
},
{
name: 'John',
id: 3
}
]
var r = arr.some(i => i.name.includes('Jack'));
console.log(r);




[#52122] Tuesday, May 7, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joanneamiyaa

Total Points: 532
Total Questions: 127
Total Answers: 98

Location: Guam
Member since Tue, Nov 3, 2020
4 Years ago
;