2016-08-30 84 views
1

我使用angularjs.I創建應用JSON記錄有JSON,如:獲得最近從具有劃時代的時間

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

我想從json的最近時間的價值。我不知道我該怎麼做。

+3

你需要這三個工具 - 'JSON.parse'解析JSON字符串...'Object.keys'得到一個數組鍵#... Array#sort'對這些鍵進行排序...然後實現所有鍵都具有相同的值,即'0',所以你浪費了時間在代碼上:p –

回答

3

最兼容的方式,最簡單的在我看來閱讀:

  1. 使用Object.keys
  2. sort()他們,如果有必要(在你的例子不是必要的)
  3. 訪問值(在你的榜樣永遠0)使用POP或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)

1
var biggest=0; 
var obj = { 
    "dps": { 
     "1455719820": 0, 
     "1455720150": 0, 
     "1455720480": 0, 
     "1455720810": 0, 
     "1455721140": 0, 
     "1455721470": 0, 
     "1455721800": 0, 
     "1455722130": 0 
    } 
    } 
for(key in obj.dps){ 
    if(biggest<key){ 
      biggest = key; 
    } 
} 

// biggest will now have the biggest timestamp 
1

你可以使用Array#reduce,執行單迴路,不需事先排序鍵。

var data = { "dps": { "1455719820": 0, "1455720150": 0, "1455720480": 0, "1455720810": 0, "1455721140": 0, "1455721470": 0, "1455721800": 0, "1455722130": 42 } }, 
 
    result = data.dps[Object.keys(data.dps).reduce(function (r, a) { 
 
     return r < a ? a : r; 
 
    }, 0)]; 
 

 
console.log(result);

1

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

 
var max = Math.max.apply(Math, Object.keys(o.dps)); 
 

 
console.log(max);