Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing a JSON array to get first five objects

I have a JSON file wherein am reading the objects and displaying them in a div. But i just need to show only five of the objects rather than all.

Below is the code which i am using

$.each(recentActdata.slice(0,5), function(i, data) {
            var ul_data = "<li><h3>"+ renderActionLink(data)+ "</h3></li>";
            $("#recentActivities").append(ul_data);
        });

But this slice doesn't seems to work. The format of my JSON is

[   
{ 
    "displayValue":"Updated Guidelines", 
    "link":"#",
    "timestamp":"29/06/2013 01:32"
},
{ 
    "displayValue":"Logging", 
    "link":"#",
    "timestamp":"28/06/2013 16:19"
},
{ 
    "displayValue":"Subscribe", 
    "link":"#",
    "timestamp":"21/06/2013 14:30"
},
{ 
    "displayValue":"Artifactory Vs Nexus", 
    "link":"#",
    "timestamp":"21/06/2013 13:39"
},
{ 
    "displayValue":"CTT - Java 7", 
    "link":"#",
    "timestamp":"20/06/2013 13:30"
},
{ 
    "displayValue":"Added Artifactory Server", 
    "link":"#",
    "timestamp":"19/06/2013 23:39"
},
{ 
    "displayValue":"Estimation Template", 
    "link":"#",
    "timestamp":"19/06/2013 23:39"
},
{ 
    "displayValue":"GZIP compression in Tomcat", 
    "link":"#",
    "timestamp":"14/06/2013 23:39"
},
{ 
    "displayValue":"HBase Basics", 
    "link":"#",
    "timestamp":"12/06/2013 23:39"
}
 ]

Please suggest how to achieve this. I can't give my JSON a name.

like image 203
roger_that Avatar asked Jul 01 '13 09:07

roger_that


1 Answers

The code you posted works fine!

Here is a demo: http://jsfiddle.net/enXcn/1/

Note how, when you are changeing the value of slice, more or less elements are displayed, which is what you discribed it should do.

HTML: <div id="recentActivities"></div>

JS:

var recentActdata = [   
{ 
    "displayValue":"Updated Guidelines", 
    "link":"#",
    "timestamp":"29/06/2013 01:32"
},
{ 
    "displayValue":"Logging", 
    "link":"#",
    "timestamp":"28/06/2013 16:19"
},
{ 
    "displayValue":"Subscribe", 
    "link":"#",
    "timestamp":"21/06/2013 14:30"
},
{ 
    "displayValue":"Artifactory Vs Nexus", 
    "link":"#",
    "timestamp":"21/06/2013 13:39"
},
{ 
    "displayValue":"CTT - Java 7", 
    "link":"#",
    "timestamp":"20/06/2013 13:30"
},
{ 
    "displayValue":"Added Artifactory Server", 
    "link":"#",
    "timestamp":"19/06/2013 23:39"
},
{ 
    "displayValue":"Estimation Template", 
    "link":"#",
    "timestamp":"19/06/2013 23:39"
},
{ 
    "displayValue":"GZIP compression in Tomcat", 
    "link":"#",
    "timestamp":"14/06/2013 23:39"
},
{ 
    "displayValue":"HBase Basics", 
    "link":"#",
    "timestamp":"12/06/2013 23:39"
}
 ];


$.each(recentActdata.slice(0,5), function(i, data) {
            var ul_data = "<li><h3>"+ data.displayValue+ "</h3></li>";
            $("#recentActivities").append(ul_data);
        });
like image 161
Stefan Avatar answered Oct 15 '22 22:10

Stefan