Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array object contains one string in angularjs

this is my code i want to check that if array contains this specific string "Identicon". and i'm looking for one line code for as solution i just want to check with if condition.

 $scope.profileImageOptions = [
                      {
                Type: "Identicon",
                Code: "identicon"
            },
            {
                Type: "MonsterID",
                Code: "monsterid"
            },

        ];

    if($scope.profileImageOptions.indexOf($rootScope.settings.defaultImage) >-1)
{
    console.log('ok');

    }
like image 373
Lakmi Avatar asked Apr 25 '17 10:04

Lakmi


1 Answers

You can use includes method in combination with some method.

some method accepts as parameter a callback provided function which is applied for every item in the array.

profileImageOptions = [
            {
                Type: "Identicon",
                Code: "identicon"
            },
            {
                Type: "MonsterID",
                Code: "monsterid"
            },

];
var exist=profileImageOptions.some(function(item){
  return item.Type.includes("Identicon");
});
console.log(exist);

Also, you can use an arrow function to simplify your code.

profileImageOptions.some(item => item.Type.includes("Identicon"))
like image 62
Mihai Alexandru-Ionut Avatar answered Sep 19 '22 15:09

Mihai Alexandru-Ionut