2016-10-27 56 views
1

我有以下幾點:檢查數組對象的多個值 - AngularJS

$scope.Items = [{"ItemId": 1, "ItemName":"Test1"}, {"ItemId": 2, "ItemName":"Test2"}, {"ItemId": 3, "ItemName":"Test3"}]; 

如果我要檢查,如果項目Id 1和2項目Id此內存在,這將是它的最佳方法?我認爲indexOf屬性應該可以工作,但是如何用它來檢查數組中是否存在對象的特定屬性值?

+0

嘗試'Array.find':https://developer.mozilla.org/en/docs/Web/JavaScr ipt/Reference/Global_Objects/Array/find – arnabkaycee

+0

任何想法如何在find()函數中添加「ItemId」的值? – 221b

+0

請參閱下面的答案。 – arnabkaycee

回答

3

您可以像使用也

$scope.firstitem=false; 
$scope.seconditem=false; 
angular.forEach($scope.Items, function (value, key) { 
      if (value.ItemId== 1) { $scope.firstitem=true; } 
      if (value.ItemId== 2) { $scope.seconditem=true; } 
     }); 
2

你可以使用lodash_.some()操作

var _ = require('lodash'); 
var Items = [{"ItemId": 1, "ItemName":"Test1"}, {"ItemId": 2, "ItemName":"Test2"}, {"ItemId": 3, "ItemName":"Test3"}]; 

var hasItem1 = _.some(Items, ["ItemId", 1]); 
var hasItem2 = _.some(Items, ["ItemId", 2]); 

console.log ("hasItem1 = "+hasItem1); 
console.log ("hasItem2 = "+hasItem2); 
2

您可以使用找到這樣的功能由你想屬性查找。

var inventory = [ 
    {name: 'apples', quantity: 2}, 
    {name: 'bananas', quantity: 0}, 
    {name: 'cherries', quantity: 5} 
]; 

function findCherries(fruit) { 
    return fruit.name === 'cherries'; 
} 

console.log(inventory.find(findCherries)); 
// { name: 'cherries', quantity: 5 } 

如果您希望過濾(即,發現多個值)可以使用filter功能是這樣的:

var arr = [ 
    { id: 15 }, 
    { id: -1 }, 
    { id: 0 }, 
    { id: 3 }, 
    { id: 12.2 }, 
    { }, 
    { id: null }, 
    { id: NaN }, 
    { id: 'undefined' } 
]; 

var invalidEntries = 0; 

function filterByID(obj) { 
    if (obj.id !== undefined && typeof(obj.id) === 'number' && !isNaN(obj.id)) { 
    return true; 
    } else { 
    invalidEntries++; 
    return false; 
    } 
} 

var arrByID = arr.filter(filterByID); 

console.log('Filtered Array\n', arrByID); 
// Filtered Array 
// [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }] 

console.log('Number of Invalid Entries = ', invalidEntries); 
// Number of Invalid Entries = 4 

編號:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

2

你可以使用lodash的_.findIndex ()運算符

var _ = require('lodash'); 
var Items = [{"ItemId": 1, "ItemName":"Test1"}, {"ItemId": 2, "ItemName":"Test2"}, {"ItemId": 3, "ItemName":"Test3"}]; 

var hasItem1 = false; 
var hasItem2 = false; 
if(_.findIndex(Items, {ItemId : 1}) != -1) { hasItem1 = true; } 
if(_.findIndex(Items, {ItemId : 2}) != -1) { hasItem2 = true; } 

console.log ("hasItem1 = "+hasItem1); 
console.log ("hasItem2 = "+hasItem2);