3

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"

3 Answers 3

4

Im 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);

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

This will returns the object not the index
0

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.