0

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?

Marc Rasmussen
  • 19,771
  • 79
  • 203
  • 364

3 Answers3

1

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

antoinestv
  • 3,286
  • 2
  • 23
  • 39
0

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

Nikki
  • 137
  • 2
  • 3
  • 17
0

Also you can use my solution of finding objects in an array. But still it will loop over all elements of an array.

Community
  • 1
  • 1
Vladimir
  • 342
  • 1
  • 8