0

I have a json data like this.

data = [{"value": "One", "value2": "1"},
{"value": "Two", "value2": "2"},
{"value": "Three", "value2": "3"},
{"value": "Four", "value2": "4"}]

I want to create dropdown with label of value and data-value of value2.

I'm able to create a dropdown by passing any one single column to a array like this.

chart_data = [];

data.forEach(function(d) {
   chart_data.push(d.value)
})

["one","two","three"] // result

With that result I create a dropdown using jquery's $.each() function.

$.each(chart_data, function(i, val) {
       $('#dropdown').append('' + val + '');
})

But over there I'm able to create using only single column.

I'm looking to create a dropdown from two column values with 1 col for the label and other for the data-value.

Konrad Gadzina
  • 3,407
  • 1
  • 18
  • 29
Unknown User
  • 3,598
  • 9
  • 43
  • 81

3 Answers3

0

Try this

data.forEach(function(d) {
  var option = "<option value='"+d.value2+"'>"+d.value+"</option>";
  $('#dropdown').append(option);
})
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

You really don't need to make a single array, I don't know why you are making that

Simply use your data field to populate your dropdown

$.each(data, function(i, obj) {
   $('#dropdown').append(new Option(obj.value, obj.value2));
});
prakash2089
  • 498
  • 4
  • 16
progrAmmar
  • 2,606
  • 4
  • 29
  • 58
0

Run the each on your data array.

$.each(data, function(i, o) {
  $('#dropdown').append('<option value="' + o.value + '">' + o.value2 + '</option>');
});
Lee
  • 2,993
  • 3
  • 21
  • 27