1

Given this DB collection structure:

{
        "_id" : ObjectId("59ba5bf6fa12aa446c097793"),
        "tab" : "tab1",
        "tabfeeds" : [
                {
                        "url" : "//url1",
                        "limit" : 4,
                        "type" : "text"
                },
                {
                        "url" : "//url2",
                        "limit" : 8,
                        "type" : "normal"
                }
        ]
}
{
        "_id" : ObjectId("59ba73a6fa12aa446c097794"),
        "tab" : "tab2",
        "tabfeeds" : [
                {
                        "url" : "//url5",
                        "limit" : 4,
                        "type" : "normal"
                }
        ]
}

I can get all the "tabs" collection like this:

router.get('/tabs', function(req, res) {
    var db = req.db;
    var collection = db.get('tabs');
    collection.find({},{},function(e,docs){
        res.json(docs);
    });
});

And then:

$.getJSON( '/feeds/tabs', function( data ) {
    $.each(data, function(){
        tablistcontent += '<th rel="' + this.tab + '">' + this.tab + '</th>';
    });
});

But how can I list every element of tabfeeds for each tab?

1 Answer 1

2

So what you have to do is create a parameter in the anonymous function you're creating in your $.each call. That will be the index of the current item you're at in the array. Then you'll use that index to get the data corresponding to that index in the array called data.

Then you'll look into the object you're on and get the tabfeeds attribute, which will be an array. Then you loop through the tabfeeds array for every tab object and do whatever you want to do with that data.

// outside up here you'll have a variable to hold tab feed data
// i'll call it tabfeedData for example
var tabfeedData = '';

// loop through all the data
$.each(data, function(tab) {

    var tabfeeds = data[tab]["tabfeeds"]; // get array of tabfeeds from data variable

    tablistcontent += '<th rel="' + this.tab + '">' + this.tab + '</th>'; 

    // loop through tabfeeds and do whatever you need to (like construct a string with attributes from the tabfeed object)
    $.each(tabfeeds, function(tabfeed) {
        tabfeedData += "<tr data-url='" + this.url + "'>";
    });

});
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.