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?
-
No. you have to iterate through the array.Ram– Ram2015年08月30日 10:35:45 +00:00Commented Aug 30, 2015 at 10:35
4 Answers 4
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");
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
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
Check the jQuery documentation for this method.
var result = $.grep(myArray, function(e){ return e.id == id; });
10 Comments
document.getElementsByClassName('.test'); vs $(".test");Array.prototype.filter method. Loading a DOM/Ajax library for filtering an object makes no sense.