0

I have an array of object like this in javascript:

var events = 
[
{
 id: 'a',
 title: 'Event 1 title'
},
{
 id: 'b',
 title: 'Event 2 title'
}
];

In order to reference event b I have to know the index of the event b, which I could find out by looping through the array and checking what is the index of the event when event's id matches b.

Is there easier way to reference event b when I know the id property of the event?

1
  • No. you have to iterate through the array. Commented Aug 30, 2015 at 10:35

4 Answers 4

2

In order to reference event b I have to know the index of the event b

Not necessarily. You can use Array.filter to get the object you need without the need of knowing it's index.

var obj = events.filter(function(obj){
   return obj.id == "b";
})[0]

or you can also use Array.prototype.find which is new in ES6 like

var obj = events.find((obj) => obj.id == "b");
Sign up to request clarification or add additional context in comments.

2 Comments

In es2015 there is Array.prototype.find() which might be more convenient.
@zerkms, I've included it. Thanks
1

Yes, don't store it as a list, store it as an object:

var events = {'a': 'Event title 1', 'b': 'Event title 2'}

and then use it like this:

events['a']

Comments

1

You could build an index over the ids of the objects in the list of events:

> var events = [{
...     id: 'a',
...     title: 'Event 1 title'
... }, {
...     id: 'b',
...     title: 'Event 2 title'
... }];
> var index = {};
> events.forEach(function(v, i) { index[v.id] = i; });
> index
{ a: 0, b: 1 }
> events[index['b']]
{ id: 'b', title: 'Event 2 title' }

1 Comment

i usually use it to speedy execute
0

Check the jQuery documentation for this method.

var result = $.grep(myArray, function(e){ return e.id == id; });

10 Comments

Please just let jquery die.
Yeah just let the most used JavaScript library die.
People forgot how to program without it. The modern vanilla JS solution is shorter than your code, but hey let's bring 80kb just for such a trivial task.
Vanilla JavaScript solution for this particular situation is shorter indeed. But for anything else is painfully longer. document.getElementsByClassName('.test'); vs $(".test");
I believe his point was why using the heavy-weight jQuery when you can simply use the Array.prototype.filter method. Loading a DOM/Ajax library for filtering an object makes no sense.
|

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.