Reputation: 20555
For the purpose of example lets have the following object:
var myobj = {id: 1, text: 'hello world', user_id: 5}
Now lets say we have an array:
var objectContainer = []
And we fill this objectContainer with x number of myobj
Now we wish to find the myobj
that has the id
value set to 30
You could use a loop but in worst case you would have to loop through the whole array before finding your value.
So my question is does JaVaScript
have a function for these situations or does AngularJs
provide additional helpers to solve this?
Upvotes: 0
Views: 2483
Reputation: 3306
You have a lot of different solutions :
Javascript FIND : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example :
var myobject = objectContainer.find(function(value){ return value.id === 1; });
Angular filter : https://docs.angularjs.org/api/ng/filter/filter
If your ids are unique you could also use a map instead of an array :
Exemple :
var myobj = {id: 1, text: 'hello world', user_id: 5};
var objectContainer = {};
objectContainer[myobj.id] = myobj;
etc
Upvotes: 1
Reputation: 342
Also you can use my solution of finding objects in an array. But still it will loop over all elements of an array.
Upvotes: 0
Reputation: 137
Your value of 'x' is the array indexer. So objectContainer[29] should point to the myobj in the 30th position.
Upvotes: 0