Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Angular / Javascript search array for object key

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 AngularJsprovide additional helpers to solve this?

Upvotes: 0

Views: 2483

Answers (3)

antoinestv
antoinestv

Reputation: 3306

You have a lot of different solutions :

  1. 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; });

  2. Angular filter : https://docs.angularjs.org/api/ng/filter/filter

  3. 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

Vladimir
Vladimir

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

Nikki
Nikki

Reputation: 137

Your value of 'x' is the array indexer. So objectContainer[29] should point to the myobj in the 30th position.

Upvotes: 0

Related Questions