I want to check if a string matches another string in an array of objects.
Here’s my code
JavaScript
x
8
1
let myArr = [{title: "fruits"}, {title: "vegetables"}];
2
//I want to match a string with the 'title' of the objects
3
4
var str = "string";
5
if ( myArr[i].title == str) {
6
//Do something
7
}
8
Advertisement
Answer
Since you’re clearly already using ES6, the most idiomatic way is using Array.includes
after map
ping the array:
JavaScript
1
7
1
let myArr = [{title: "fruits"}, {title: "vegetables"}];
2
3
var str = "string";
4
5
let match = myArr.map(obj => obj.title).includes(str);
6
7
console.log(match);