Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object by its property in array of objects with AngularJS way

I have a array like below

var myArray = [{'id':'73','name':'john'},{'id':'45','name':'Jass'}, etc.] 

Now I have an id 73 how to select this particular object from the array. I see I can do this in jQuery easily with grep Is there any angular way of doing this?

Since most user developing app with angular always get data from array of objects(mostly for table) there should be a helper function for this?

So that I can change the data of the row with the ID of the row by updating the array of object.

I don't want to bind this in view. I want to manipulate the data and update the data withing function.

For Example. I have a table listing. If end user edit a row from the table I have the ID of the object so after end user hit save, I need to update the array and then back to table listing.

like image 967
rram Avatar asked Oct 28 '16 14:10

rram


People also ask

How do you find the object property of an array?

Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

How do you check if an object is present in an array in AngularJS?

Answer: Use the Array. isArray() Method You can use the JavaScript Array. isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .

How do you check if an element is present in an array in angular?

The indexOf() method searches the array for the specified item, and returns its position. And return -1 if the item is not found.

How do you use indexOf for array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.


2 Answers

you can use angular's filter https://docs.angularjs.org/api/ng/filter/filter

in your controller:

$filter('filter')(myArray, {'id':73})  

or in your HTML

{{ myArray | filter : {'id':73} }} 
like image 142
M B Avatar answered Sep 23 '22 10:09

M B


How about plain JavaScript? More about Array.prototype.filter().

var myArray = [{'id': '73', 'name': 'john'}, {'id': '45', 'name': 'Jass'}]    var item73 = myArray.filter(function(item) {    return item.id === '73';  })[0];    // even nicer with ES6 arrow functions:  // var item73 = myArray.filter(i => i.id === '73')[0];    console.log(item73); // {"id": "73", "name": "john"}
like image 26
TimoStaudinger Avatar answered Sep 23 '22 10:09

TimoStaudinger