$.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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742403841a4437444.html
评论列表(0条)