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

13,889

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"))
Share:
13,889
Lakmi
Author by

Lakmi

life runs on code

Updated on June 11, 2022

Comments

  • Lakmi
    Lakmi almost 2 years

    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');
    
        }