Skip to content
Advertisement

How to compare a string with a value of an object in an array

I want to check if a string matches another string in an array of objects.

Here’s my code

let myArr = [{title: "fruits"}, {title: "vegetables"}];
//I want to match a string with the 'title' of the objects 

var str = "string";
if ( myArr[i].title == str) {
    //Do something 
}

Advertisement

Answer

Since you’re clearly already using ES6, the most idiomatic way is using Array.includes after mapping the array:

let myArr = [{title: "fruits"}, {title: "vegetables"}];

var str = "string";

let match = myArr.map(obj => obj.title).includes(str);

console.log(match);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement