Holly Johnson Holly Johnson - 14 days ago 8
Javascript Question

From Json Get vlaue of key Javascript

I am trying to do an api call to get a list of subcategories.
my json looks like this

{
"description": "Flower",
"name": "Flower",
"parent_id": "1"
},
{
"description": "Moon",
"name": "Moon",
"parent_id": "1"
}
]




This is what i have attepted so far.

<script type="text/javascript">
$('button').click(function() {

$.ajax({
url: "/api/subcategories?sstr=ball",
dataType: 'json',
type: "GET"
})
.done(function(data) {
$('.results').append('<ul class="list"></ul>');
$.each(data, function(key, value) {
console.log(data)
$('.list').append('<li>' + key + ': ' + value + '</li>');
});
})
.fail(function(event) {
alert(event.status);
});
});
</script>


The result i get is
0: [object Object]
1: [object Object]
2: [object Object]

what i would like is the list of names.

Answer

Where value is the array element which is an object instead get its name property.

$('.list').append('<li>' + key + ': ' + value.name + '</li>');

Since it's an array you can use JavaScript Array#forEach method also.

$('.results').append('<ul class="list"></ul>');data.forEach(function(value, key) {
  $('.list').append('<li>' + key + ': ' + value.name + '</li>');
});

Or you can reduce it to a single append statement by generating the HTML string using Array#map and Array#join methods.

 $('.results').append(
   '<ul class="list">' +
   data.map(function(value, key) {
     return '<li>' + key + ': ' + value.name + '</li>');
   }).join('') + 
  '</ul>'
 );