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?

3
  • Does the script start after the onload event? Commented Dec 18, 2013 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 question. Commented Dec 18, 2013 at 21:06
  • 1
    Please don't support IE8. Commented Dec 18, 2013 at 21:08

2 Answers 2

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>');
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.