【发布时间】:2017-08-08 09:05:06
【问题描述】:
这是我的对象数组:
$scope.choices = [
{
id: 0,
product: [{id:'0'}]
},
{
id: 10,
product: [{id:'5'}]
}
];
如何找到 id 值“10”的索引号?
【问题讨论】:
标签: javascript angularjs arrays
这是我的对象数组:
$scope.choices = [
{
id: 0,
product: [{id:'0'}]
},
{
id: 10,
product: [{id:'5'}]
}
];
如何找到 id 值“10”的索引号?
【问题讨论】:
标签: javascript angularjs arrays
你可以用这个:
var reqIndex;
$scope.choices.forEach(function(choice, index) {
if (choice.id === 10) {
reqIndex= index;
return
}
})
【讨论】:
试试这个
$scope.choices.findIndex(function(x) {
return x.id==10;
});
【讨论】:
让下面是你要在数组中搜索的对象
var searchObject={
id: 0,
product: [{id:'0'}]
};
现在使用以下
$scope.choices.indexOf(searchObject);
希望这会有所帮助:)
如果你喜欢使用纯javascript并且使用没问题,你可以使用以下
function findWithAttr(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
findWithAttr(choices, 'id', 10);
或者,您可以使用以下函数
$scope.findIndex=function(){
angular.forEach( $scope.choices,function(object,index){
console.log(object);
if(object.id==10){
console.log('index'+index);
}
})
};
【讨论】:
您可以使用Object.keys() 检索您对象的所有键,然后对其进行迭代以查找是否有一个具有相应值的键。
【讨论】: