最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论
 $.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.

发布评论

评论列表(0)

  1. 暂无评论