2017-04-25 3 views
1

das ist mein Code Ich möchte überprüfen, ob Array diese spezifische Zeichenfolge "Identicon" enthält. und ich suche nach einem Zeilencode für eine Lösung, die ich nur mit Bedingung überprüfen möchte.Wie überprüft man, ob ein Array-Objekt eine Zeichenfolge enthält in angularjs

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

     ]; 

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

    } 
+0

Mögliche Duplikate von [Holen Sie JavaScript-Objekt aus Array von Objekten nach Wert oder Eigenschaft] (http://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects- by-value-or-property) –

+0

@Lakmi, es funktioniert meine Lösung? –

+0

@Nguyen Thanh Nein, weil ich nach einem Zeilencode suche. Ich habe eine Lösung von diesem Post bekommen. thnx – Lakmi

Antwort

1

Sie können mit some Methode includes Verfahren in Kombination verwendet werden.

some Methode akzeptiert als Parameter eine callback zur Verfügung gestellte Funktion, die für jeden Artikel in der array gilt.

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

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

Sie können aber auch lambda Ausdrücke verwenden.

profileImageOptions.some(a=>a.Type.includes("Identicon")) 
+1

thnx diese arbeit für mich – Lakmi

0

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

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

des some in Javascript verwenden lassen:

$scope.profileImageOptions.some(element => element.Type.includes('Identicon')); 
+0

Thnak du hilfst mir. – Lakmi

+0

Gut zu wissen :) –

0

Sie mögen unten tun können:

<!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> 

Überprüfen Sie die example

Verwandte Themen