Hagbard
Hagbard

Reputation: 575

How to increment an index value using jQuery

The server returns JSON in the format

"games": [{
    "gameType": "RPG",
    "publishers": [{
        "publisher": "Square",
        "titles": [{
            "title": "Final Fantasy",
            "gameReleases": [ 2006, 2008, 2010, 2012, 2013, 2014 ]
        }]
    }]
}]

There is no numbered index which i need to populate a drop down later in the code, and i'm trying to add dynamically through Jquery.

So if RPG was selected this would be equivalent to 1, if the next item was Strategy this would be number 2 etc. This would help me pass in items dynamically to a pluck command:

var i = $('gametypecombo').attr('value');
var getGameType = _.pluck(jsonData.gameType[i].publishers, 'publisher');

How would i add an index to item in order to achieve this. My current code to populate the gameType drop down is:

var subGame = _.pluck(jsonData.games, 'gameType');
var gameType = _.map(subGame , function (val) {
return '<option value="' + index + '">' + val + '</option>';
}).join();

So it's the index in this code which i need to be an incrementing value. Tried using a loop and _.each but no luck.

Thanks

EDIT: Just to expand on the comment - when i'm outputting the index to the console it seems to work, each item in the drop down has an index value, then when i'm selecting an item from the drop down and outputting it to console the value is correct for that selection. However as soon as i pass that as a variable to:

var getGameType = _.pluck(jsonData.gameType[i].publishers, 'publisher');

I get the error, any advice?

Upvotes: 0

Views: 1629

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

You can use a data-* attribute to store the index and the fetch it using .data()

var subGame = _.pluck(jsonData.games, 'gameType');
var gameType = _.map(subGame, function (val, i) {
    return '<option value="' + index + '" data-index="' + i + '">' + val + '</option>';
}).join();

then

var index = $('gametypecombo').find('option:selected').data('index')
var i = $('gametypecombo').val();
var subGame = _.pluck(jsonData.games, 'gameType');
var getGameType = _.pluck(subGame.publishers, 'publisher');

Upvotes: 1

Aleks G
Aleks G

Reputation: 57316

Considering you're using jQuery, you can use each method with two parameters in the callback function - the first one will be index:

$.each(games, function(idx, obj) {
    //now idx is your index
    //and obj is the object corresponding to your index
});

Upvotes: 1

prady00
prady00

Reputation: 741

var index = 0; //global variable
var subGame = _.pluck(jsonData.games, 'gameType');
var gameType = _.map(subGame , function (val) {
return '<option value="' + index++ + '">' + val + '</option>';
}).join();

Upvotes: 1

Related Questions