jhonleg jhonleg - 3 months ago 8
HTML Question

Populate div with select from multi array JSON

I'm really new on json, and I'm trying to show some info from json data, via select. Its possible??

[
{
"id": 1,
"country": "Spain",
"more": [
{
"city": "Barcelona",
"age": 1992,
"language": "catalan",
},
{
"city": "Madrid",
"age": 2001,
"language": "spanish",
}
]
},
{
"id": 2,
"country": "Portugual",
"more": [
{
"city": "Porto",
"age": 2009,
"language": "portuguese",
},
{
"city": "Madeira",
"age": 1997,
"language": "portuguese",
}
]
}
]


so, I have a select that works with this .js file:

var json = '[{"id":1,"country":"Spain","more"[{"city":"Barcelona","age":1992,"language":"catalan",},{"city":"Madrid","age":2001,"language":"spanish",}]},{"id":2,"country":"Portugual","more":[{"country":"Porto","age":2009,"language":"portuguese",},{"country":"Madeira","age":1997,"language":"portuguese",}]}]';

var items = JSON.parse(json);
var $selectElement = $("#list");

$(items).each(function(){
var option = '<option value="' + this.id + '">' + this.city + '</option>';
$selectElement.append(option);
});


this is my HTML

<div class="form-group">
<label>Select the city:</label>
<select class="form-control" id="list" name="list">
</select>
</div>

<div id="info">
<h1><span class="city"> </span></h2>
<h2><span class="age"> </span></h2>
<h3><span class="language"> </span></h3>
</div>


and now I would like to make when select the Country, populate an HTML "more" -from json- information, and change when I change the option in a select.
I will be grateful if someone can help me!

EDIT -- All of answers works perfectly. I accepted the question that I chose to use! -- Thanks!

Answer

Your JSON is an Array with Object with Array with Object. Therefore you should loop through the arrays to get the values you need for selected option. This Fiddle should work.

 $('body').on('change', '#list', function() {
  var selectedOption = this.value;
  $(items).each(function() {
    if (this.id.toString() === selectedOption) {
      $('#info').html(returnData(this.more));
      return;
    }
  })
})

var returnData = function(arr) {
  var t = '';
  console.log(arr)
  $(arr).each(function() {
    var objKeys = Object.keys(this);
    console.log(objKeys)
    var s = ''
    for (var i = 0; i < objKeys.length; i++) {
      s += '<h' + (i + 1) + '><span class="' + objKeys[i] + '">' + this[objKeys[i]] + '</span></h' + (i + 1) + '>';
      console.log(s, objKeys[i])
    }
    t += s;
  });
  return t;
}