Reputation: 914
Currently, I have an array of objects, that looks like this:
var arr = [{
id: UNIQUE_ID,
title: 'TITLE'
}, {
id: UNIQUE_ID,
title: 'TITLE'
}];
What is bothering me here, is that in particular cases I have to loop through the array and display data for matching ID. I want to just fetch everything for that particular object, thas has the ID I want, and that's it. It would be a lot easier for me if the array looked more like this:
var arr = [{
id: {
title: 'TITLE'
},
id: {
title: 'TITLE'
}
}]
The ID comes from a result of a method that generates a random number, so I'll need to put a variable or a method call for this id.
I'm not sure this is possible, since I found no particular example on this, but I'd like to hear another solutions as well.
Upvotes: 6
Views: 30883
Reputation: 2345
With the help of UnderscoreJs:
var arr= [{
id: '1',
title: 40
}, {
id: '2',
title: 40
}, {
id: '1',
title: 60
}];
var res = _.groupBy(arr, function(x){ return x.id; });
res["1"];
Result:
[{
id: '1',
title: 40
}, {
id: '1',
title: 60
}]
http://jsbin.com/jifabuva/1/edit
Upvotes: 0
Reputation: 1074148
You can do that, by removing the array entirely, just using an object:
var items = {};
items["some id"] = {title: 'first title'};
items["another id"] = {title: 'second title'};
Or if you have the key in a variable:
var key = "a third id";
items[key] = {title: 'third title'};
Later, if you wanted to look up one of those entries based on a key:
var key = "another id";
You'd do it like this:
console.log(items[key].title); // "second title" (if key is "another id")
If you need to know what all of the keys in the object are, you can use Object.keys
:
var arrayOfKeys = Object.keys(obj);
(Note that Object.keys
is an ES5 feature; on older browsers, you need to add a shim for it, which is trivial.)
Note the way I populated the object in the first code block above. If you can hardcode the keys, you can do that with an object initializer:
var items = {
"some id": {title: 'first title'},
"another id": {title: 'second title'}
};
...but you can't do it that way if you want to use a variable for the key name, because you can't put the variable on the left-hand side of the :
(it'll look like a literal key name). That is, if you have
var key = "a third id";
then this won't work:
var items {
key: {title: "third title"} // <==== Doesn't do what we want
};
The key would be "key"
, not "a third id"
(just like the title
key we've been using). That's why in the first block above, I created the object and then set the properties separately afterward.
Upvotes: 19
Reputation: 2156
What you're asking for far is call indexing. You can easily achieve it by structuring your data as such:
var arr = {
1: {
title: 'TITLE'
},
2: {
title: 'TITLE'
}
};
You don't even have to traverse the now indexed array, since each entry is accessible through its index:
var needle = array[id];
Upvotes: 0