Monday 20 November 2017

javascript - Check if value exists in the array (AngularJS)

itemprop="text">



Currently I'm
using the forEach()-method of angular to check the new value
with the array of objects. But that's the wrong approach because for example in the list
are 20 objects. When I'm creating an object with an existing article then the
if-statement in forEach tells one time the article is existing and 19 times it
isn't.



The following
code:



var list =
[];


articlelist.forEach(function (val) {

list.push(val.artNr);
});

$log.info(list);


The
articlelistcontains all 20 objects. For comparing I only need
the artNr. Because when the User create a new article then
should be an if-Statement to check if the added artNr is already
exists.



$scope.createItem =
function (createItem) {

if(list.artNr === createItem.artNr)
{
$scope.message = 'artNr already exists!';

}
...
};


The
problem is, that list.artNr returns me "undefined" because the list variable is an
array:






list output in console => Array ["AB001", "AB002", "AB003",
"AB004"]
,



createItem output:
=> Object { artNr: "AB001", description: "New Article"
...}




How
can I compare the new created object with the array from the list
variable?



Answer




You could use
indexOf
function.



if(list.indexOf(createItem.artNr)
!== -1) {

$scope.message = 'artNr already
exists!';
}


More
about indexOf:




No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...