我有以下内容:
$scope.Items = [{"ItemId": 1, "ItemName":"Test1"}, {"ItemId": 2, "ItemName":"Test2"}, {"ItemId": 3, "ItemName":"Test3"}];
如果我想检查其中是否存在ItemId 1和ItemId 2,那么最佳方法是什么?我相信indexOf
属性应该可以工作,但如何用它来检查数组中是否存在对象的特定属性值?
答案 0 :(得分: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; }
});
答案 1 :(得分:3)
你可以使用这样的find函数来找到你想要的属性。
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 :(得分:2)
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);
答案 3 :(得分: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);