1

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

2
  • Did my answer help at all? Commented Mar 17, 2014 at 1:49
  • I've tried following the fiddle but keep getting an error: Uncaught TypeError: Cannot read property '[object Array]' of undefined I'm using the same code (other than my first drop down doesn't have option values - as it's populated dynamically). Not sure how to get over this. Commented Mar 17, 2014 at 9:03

1 Answer 1

1

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);                          
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.