stinkysGTI
stinkysGTI

Reputation: 611

Loop through multiple values within an object

What I'm trying to do is pretty simple. I have this:

var loopTest = {

    Test1: {
                date : ['November 2011', 'a new date']
              },

    Test2: {
                date : 'January 2012'
              }

};

and using a for...in like so:

for(var key in loopTest) {
    $('.content').append('- '+loopTest[key].date+'<br />');
}

I want to make the Test1.date values display as separate elements. Currently, they're one string. How do I go about this?

Here's the fiddle: jsFiddle

Upvotes: 2

Views: 2476

Answers (5)

George
George

Reputation: 36794

Use $.isArray() to test whether loopTest[key].date is an array or not. If it is, join up the dates inside with some <br>s and a hyphen. Else, append the string as it is.

for(var key in loopTest) {
    if($.isArray(loopTest[key].date)){
        var content = '- ' +  loopTest[key].date.join('<br />- ') + '<br />';
    } else {
        var content = '- ' + loopTest[key].date + '<br />';
    }
    $('.content').append(content);
}

Just one of the many ways you could go about it.

JSFiddle

Upvotes: 2

Himanshu Tanwar
Himanshu Tanwar

Reputation: 906

for(var key in loopTest) {
    var date = loopTest[key].date;
    date = date.join ? date.join("<br>- ") : date
    $('.content').append('- ' + date + '<br />');
}

Upvotes: 1

labroo
labroo

Reputation: 2961

another solution :)

var store = [];
for (var key in loopTest) {
    if (!loopTest.hasOwnProperty(key)) continue;
    var date = loopTest[key]["date"];
    if (date.constructor === Array) {
        for (var j in date) {
            if (!date.hasOwnProperty(j)) continue;                
            store.push('<p>-', date[j], '</p>');
        }
    } else {
            store.push('<p>-', date, '</p>');
    }
}
$('.content').append(store.join(''));

Upvotes: 0

Miguel
Miguel

Reputation: 20633

Keep it short and sweet

for (var key in loopTest) {
    [].concat(loopTest[key].date).forEach(function(date) {
        $('.content').append('- ' + date + '<br />');
    });
}

http://jsfiddle.net/aft37vq8/6/

Upvotes: 1

Hoyen
Hoyen

Reputation: 2519

Check if the date is a array and loop through it:

for (var key in loopTest) {

    if(Object.prototype.toString.call(loopTest[key].date) === '[object Array]') {
        for (var i = 0; i < loopTest[key].date.length; i++) {
            $('.content').append('- ' + loopTest[key].date[i] + '<br />');
        }
    } else {
        $('.content').append('- ' + loopTest[key].date + '<br />');
    }
}

Upvotes: 1

Related Questions