What is the best way to search a particular parameter of an object array in Angular?
I populate my array from an Angular foreach :
$scope.arrayiwanttosearch = [];
angular.forEach(data, function(value, key) {
try{
var arrstring = new Array();
arrstring = value.img.split(',');
obj.name = value.name;
obj.selectedcolor = arrstring[0];
obj.colors = value.img;
obj.ischanging = false;
$scope.arrayiwanttosearch.push(obj);
}
catch(ex){
}
})
I can only use array.index of when its an array without objects, is there a way to do this without using a for loop? Im trying to find the index of the object that has the obj.name == "test"
What is the best way to search a particular parameter of an object array in Angular?
I populate my array from an Angular foreach :
$scope.arrayiwanttosearch = [];
angular.forEach(data, function(value, key) {
try{
var arrstring = new Array();
arrstring = value.img.split(',');
obj.name = value.name;
obj.selectedcolor = arrstring[0];
obj.colors = value.img;
obj.ischanging = false;
$scope.arrayiwanttosearch.push(obj);
}
catch(ex){
}
})
I can only use array.index of when its an array without objects, is there a way to do this without using a for loop? Im trying to find the index of the object that has the obj.name == "test"
Share Improve this question asked Jun 16, 2017 at 9:10 Gaz SmithGaz Smith 1,1082 gold badges19 silver badges31 bronze badges3 Answers
Reset to default 4Im trying to find the index of the object that has the obj.name == "test"
This is a straight use of findIndex.
var arrayiwanttosearch = [
{
name : "nottest"
},
{
name : "test"
}
];
var index = arrayiwanttosearch.findIndex(obj => obj.name === "test");
console.log(index);
You can use the native javascript 'filter' which will bring back all the matching members of the array, or 'find' which brings back the first one it finds, or 'findIndex';
// This finds the first matching array element with an object property === 2
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.find((item) => item.a === 2);
// The filter does the same but brings back all matching elements;
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.filter((item) => item.a === 2);
// The index result;
$scope.arr = [{a:2,b:3}, {a:2,b:4}];
$scope.result = $scope.arr.findIndex((item) => item.a === 2);
ES6 JS notation, but easy to adapt for ES5 JS.
You can use Array.prototype
to get the index value in an array of objects.
var index = $scope.arrayiwanttosearch.indexOfname("test");
Array.prototype.indexOfname = function(name) {
for (var i = 0; i < this.length; i++)
if (this[i].name === name)
return i;
return -1;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742269310a4412397.html
评论列表(0条)