Issue
I am quite new to javascript/angular and was pondering whether or not there is an easy way to grab the first item in a javascript object/array.
EDIT: I do have control at this point in time in how I format the array, so perhaps there is a better way to do this using ID as keys?
Lets say I want to match the first item in the array. My thinking is to simply loop through the object checking the ID value.
The js function may look something like this:
app.controller('gamesController',function(){
//Function to load the games
this.loadGameIntoModal = function(game_id){
for (i=0;i<=length(games);i++){
if (games[i]['id'] === game_id)
{
this.games = games[i]['id'];
//Load the modal
$("#game_modal").modal();
break;
}
}
}
});
So my question is simply, is there a better way to do this than to use a loop?
var games = [
{
id : 1,
name : 'ABC Games',
games : [
{
id : 1,
name : 'ABC 1',
},
{
id : 2,
name : 'ABC 2',
} ,
{
id : 3,
name : 'ABC 3',
}
]
},
{
id : 2,
name : 'XYZ',
games : [
{
id : 4,
name : 'XYZ 1',
},
{
id : 4,
name : 'XYZ 2',
} ,
{
id : 5,
name : 'XYZ 3',
}
]
}
];
Solution
There are several different ways to do this, as other answers have valid suggestions. You mentioned that you're willing to restructure your object a bit. So this is an alternative that I've used:
var games = {
1: {id : 1,
name : 'ABC Games',
games : [
{
id : 1,
name : 'ABC 1',
},
{
id : 2,
name : 'ABC 2',
}
]
},
2: {id : 2,
name : 'XYZ',
games : [
{
id : 1,
name : 'XYZ 1',
},
{
id : 2,
name : 'XYZ 2',
}
]
},
}
With this structure, the ID is also the object's key. This has the advantage, that now you can just pass an ID, and reference it directly without loops. games['1'].name //ABC Games
.
And just for convenience, we leave the id
property within each object to make it easier for referencing later if needed.
Answered By - EnigmaRM
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.