javascript - How to get the last element of a json file with jquery - Stack Overflow

$.getJSON('.file-read?filename='+filename+'&parameter='+parameter, function(dat

 $.getJSON('./file-read?filename='+filename+'&parameter='+parameter, function(data) {
var firstElement = data[0][0];
var lastElement =  ?
});

I try to find out the last Element in my JSON file.

My JSON File looks like this:

[[1392418800000,6.9],[1392419400000,7],[1392420000000,7.1],[1392420600000,7.2],[1392421200000,7.2]]

can anybody help me to read extract the last date(1392421200000) ?

 $.getJSON('./file-read?filename='+filename+'&parameter='+parameter, function(data) {
var firstElement = data[0][0];
var lastElement =  ?
});

I try to find out the last Element in my JSON file.

My JSON File looks like this:

[[1392418800000,6.9],[1392419400000,7],[1392420000000,7.1],[1392420600000,7.2],[1392421200000,7.2]]

can anybody help me to read extract the last date(1392421200000) ?

Share asked Mar 18, 2014 at 10:37 zoom23zoom23 7142 gold badges12 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Just pick the (length - 1)th element with this:

var lastElement = data[data.length-1][0];

Another way is to use array methods, e.g. pop which will return the last element of the array:

var lastElement = data.pop()[0];

N.B.: The first approach is the fastest way of picking the last element, however the second approach will implicitly remove the last element from data array. So if you plan to use the initial array later in your code, be sure to use either the first method or alternative solution provided by @matewka.

VisioN's answer is nice and easy. Here's another approach:

var lastElement = data.slice(-1)[0];
// output: [1392421200000,7.2]

Negative number in the slice method makes the slice count from the end of the array. I find this method more pact and simpler but the disadvantage is that it returns a smaller, 1-element array instead of the element you wanted to fetch. If you want to fetch only the timestamp you'd have to add another [0] to the end of the expression, like this:

var lastElement = data.slice(-1)[0][0];
// output: 1392421200000

You can use :

var data = " any json data";
var lastelement = data[ Object.keys(obj).sort().pop() ];

Object.keys (ES5, shimmable) returns an array of the object's keys. We then sort them and grab the last one.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742403841a4437444.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信