admin管理员组文章数量:1336099
$.getJSON('./file-read?filename='+filename+'¶meter='+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+'¶meter='+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 badges3 Answers
Reset to default 3Just 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.
本文标签: javascriptHow to get the last element of a json file with jqueryStack Overflow
版权声明:本文标题:javascript - How to get the last element of a json file with jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742403841a2468416.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论