简体   繁体   中英

Looping through a nested JSON object based on Drop Downs

I'm trying to iterate over a nested JSON object and return the values in different select boxes.

This is my JSON:

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

So when RPG is selected, the publishers drop down shows Square etc.

Currently i'm doing:

$('select#gameTypeCombo').on('change', function() {
    var getPublisher = _.pluck(info.games[0].gameType[0], 'publisher');
    var preparePublisher = _.map(getPublisher, function(val){ return '<option>' + val + '</option>';}).join();  
    $('select#publisher').html (preparePublisher).selectpicker('render');                          
})

Which populates the publisher box - but as im using [0] only the first one is selected, and it's no way of populating the subsequent drop downs.

I've been looking at $.each but can't get it to work.

Any advice appreciated

Here is a working fiddle that populates the second select based on the first select's value:

var info = {
    "games": [{
        "gameType": "RPG",
        "publishers": [{
            "publisher": "Square"
        }]
    },{
        "gameType": "Other",
        "publishers": [{
            "publisher": "Someone"
        }]
    }]
};

$('select#gameTypeCombo').on('change', function(e) {
    var $elem = $(this);
    var index = $elem.val();
    var getPublisher = _.pluck(info.games[index].publishers, 'publisher');
    var preparePublisher = _.map(getPublisher, function(val){ return '<option>' + val + '</option>';}).join();  
    $('select#publisher').html (preparePublisher);                          
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM