0

I have a json object that contains an array of objects with similar properties. I'm trying to iterate through the array for each of the objects and display their individual properties. Here's what I have so far...

Object.keys(jsoncont)
    .sort(function(a,b) {
        return b.localeCompare(a)
})
.forEach(function(key) {
    var val = jsoncont[key];

    $('#contactSearchResults').html('<div class="resultset"><input type="radio" name="customer_c_id" value="' + val.id + '" /></div><div class="resultset">' + val.first + '</div><div class="resultset">' + val.last + '</div><div class="resultset">' + val.email + '</div>');

});

This is only returning one object in the array. Can someone explain to me how to iterate through all the objects instead of just returning the first result in the key?

Mikarma
  • 89
  • 1
  • 2
  • 9
  • Does the script start after the onload event? – Wayne Dec 18 '13 at 21:04
  • Just as a side note, be mindful when using `Object.keys` as it's only supported in ***IE >= 9***. For more information, see [this](http://stackoverflow.com/questions/13723805/ie-issue-object-keysvalue-length-not-supported) question. – War10ck Dec 18 '13 at 21:06
  • 1
    Please don't support IE8. – Kevin Dec 18 '13 at 21:08

2 Answers2

1

Probably because you're setting the content of #contactSearchResults each iteration. Try changing it to append if you want to print them all out to the DOM

$('#contactSearchResults').append('<div class="resultset"><input type="radio" name="customer_c_id" value="' + val.id + '" /></div><div class="resultset">' + val.first + '</div><div class="resultset">' + val.last + '</div><div class="resultset">' + val.email + '</div>');
Kevin
  • 1,934
  • 1
  • 15
  • 10
0

try this:

var allitems = "";
Object.keys(jsoncont)
.sort(function(a,b) {
    return b.localeCompare(a)
})
.forEach(function(key) {
    var val = jsoncont[key];

    allitems += '<div class="resultset"><input type="radio" name="customer_c_id" value="' + val.id + '" /></div><div class="resultset">' + val.first + '</div><div class="resultset">' + val.last + '</div><div class="resultset">' + val.email + '</div>';
});
$('#contactSearchResults').html(allitems)
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35