1

I want to retrieve data from an object, and I need to make several iterations. I have another object inside the first.

Here is what I try to do

for (var site in dataArray) {
    var itemList = site + ' - ' + dataArray[site].username + ' - ' + dataArray[site].followers + '<div class="detail"></div>' + '<br>';

    $('.test').append(itemList);

    for (var key in dataArray[site].details) {
        var itemDetail = ' - ' + key + ' ' + dataArray[site].details[key];

        $('.detail').append(itemDetail);
    }
}

But when I did this code, the first element append, receive all the key/value from the others details objects. I only want to display the details object related with his site parent site object.

Here is a fiddle : http://jsfiddle.net/JeremDsgn/7EX6M/

Thanks!

2
  • I couldn't understand what you want to achieve? Commented Jun 7, 2014 at 15:55
  • I want to iterate through the first object and after through the second object (details) but maybe I don't need the two for...in loop to achieve this. Commented Jun 7, 2014 at 15:58

1 Answer 1

3

That's because your selector $('.detail') selects all elements with class detail.

Try using the DOM instead of strings. I give you this as a personal advice. I used to append HTML via strings just like you're doing it now. Since I started using DOM objects as they are actually meant to be used, the javascript language became times more pleasant to work with.

for (var site in dataArray) {
    var itemList = site + ' - ' + dataArray[site].username + ' - ' + dataArray[site].followers;

    var details = document.createElement('div');
    details.className = 'detail';

    for (var key in dataArray[site].details) {
        var itemDetail = ' - ' + key + ' ' + dataArray[site].details[key];

        $(details).append(itemDetail);
    }

    $('.test').append(itemList).append(details);
}
Sign up to request clarification or add additional context in comments.

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.