6

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

    }
Lakmi
  • 1,379
  • 3
  • 16
  • 27

3 Answers3

6

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"))
rhysclay
  • 1,645
  • 3
  • 22
  • 42
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

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

        ];
var result = arr.some(element => element.Type.includes('Identicon'));
console.log(result)

Let's use some in Javascript:

$scope.profileImageOptions.some(element => element.Type.includes('Identicon'));
taile
  • 2,738
  • 17
  • 29
0

You can do like below:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ result[0].Type == "Identicon" ? "OK" : "Not OK"}}</p>

</div>

<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.profileImageOptions = [
                      {
                Type: "Identicon",
                Code: "identicon"
            },
            {
                Type: "MonsterID",
                Code: "monsterid"
            },

        ];

        $scope.result = $scope.profileImageOptions.filter(function(res){
        return res.Type ==  "Identicon";});
});
</script>

</body>
</html>

Check the example