marcel marcel - 23 days ago 9
HTML Question

jquery data list is not passing into the html element

I am reading a JSON file and getting the values for

type
. I want to pass it as a list to the HTML element
#myList
yet what I get is
[object object]
in place of the list. However my
console.log
is showing exactly what I want, which is stored in
o.type
.

$(document).ready(function() {
$.getJSON("data.json", function(obj) {
$('#myList').data('types', obj.types.map(function(o) {
console.log(o.type);
return o.type;
})).append('<li>' + obj + '</li>');
});
});


Could somebody help to fix this?

Answer

While concatenating an object with a string which concatenates [object object] to the string since toString(obj) result [object object] .

Use Array#map method to generate the HTML code and append to the element.

$(document).ready(function() {
    $.getJSON("data.json", function(obj) {
        $('#myList').data('types', obj.types.map(function(o) {
            console.log(o.type);
            return o.type;
        })).append(obj.types.map(function(o) {
            return '<li>' + o.type + '</li>';
        }).join(''));
    });
});