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?

2
  • 2
    see filter Commented Jun 30, 2015 at 10:01
  • @Hacketo can this be used to retrieve the item in a controller / service? Commented Jun 30, 2015 at 10:04

3 Answers 3

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

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

2 Comments

find is es6 . Also you should provide english links on StackOverflow.
Indeed but you can still provide an implementation of find.
0

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

2 Comments

Yeah that would be true if you put them in cronologicly but if you put them in at random this would not
try Array.findIndex("what you want to search);
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.