Getting JSON [Object object] from rest interface

Viewed 27

I have a simple web service using apache camel that, on HTTP GET, returns column names from a database as JSON.

The GET is bound to my front end by a button click. On click in the developer tools I can see the XHR data returning the values I expect, however I can't seem to pull them out programmatically.

Example of the data I am trying to read:

[{"COLUMN_NAME":"EID"},{"COLUMN_NAME":"USERID"},{"COLUMN_NAME":"LAST_UPDATE"},{"COLUMN_NAME":"LAST_UPDATED_BY"},{"COLUMN_NAME":"CREATED_DATE"}]
$(document).ready(function () {
    $('#getButton').click(function () {
    $.ajax({
        url: 'http://localhost:8090/rs/persons'
    }).then(function(data) {
            $.each(data, function(index, value) {
            $('#dropList').append(
                $('<option>', {text: value})
            )})
        });
    });
});

With the above code, my select list (dropList) populates with Object object for each item in the returned set.

Please advise, thanks.

1 Answers

value refers to the object. To append the text you need to refer to the property of that object:

$('<option>', {
  text: value.COLUMN_NAME // note the property name here
});

Also note that you can optimise the logic a little by creating a single string of HTML so that you only need to call append() once:

var data = [{
  "COLUMN_NAME": "EID"
}, {
  "COLUMN_NAME": "USERID"
}, {
  "COLUMN_NAME": "LAST_UPDATE"
}, {
  "COLUMN_NAME": "LAST_UPDATED_BY"
}, {
  "COLUMN_NAME": "CREATED_DATE"
}]

var html = data.map(function(o) {
  return `<option>${o.COLUMN_NAME}</option>`; 
}).join('');
$('#dropList').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropList"></select>

Related