Karan Karan - 3 months ago 7
JSON Question

get most recent record from json having epoch time

I am creating app using angularjs.I have json like:

{
"dps": {
"1455719820": 0,
"1455720150": 0,
"1455720480": 0,
"1455720810": 0,
"1455721140": 0,
"1455721470": 0,
"1455721800": 0,
"1455722130": 0
}
}


I want to get the value of most recent time from json. I don't know how can i do this.

Answer

The most compatible way and easiest to read in my opinion:

  1. Use the Object.keys
  2. sort() them if necessary (in your example not necessary)
  3. access the value (in your example always 0) using pop or arr[arr.length-1]

var o = {
    "dps": {
      "1455719820": 10,
      "1455720150": 90,
      "1455720480": 110,
      "1455720810": 560,
      "1455721140": 670,
      "1455721470": 120,
      "1455721800": 9,
      "1455722130": 130
    }
  }

// just sorting
var arr = Object.keys(o.dps).sort(); // your keys were actually already sorted
console.log(arr);

// To get the latest value; 
var newest = arr.pop();
var val = o.dps[newest];
console.log(newest,val)

Comments