2016-09-15 94 views
-1

除了偶爾的jQuery選擇器和元素修改之外,我對javascript的評價也不是很高。對於我遇到的問題,我需要按日期過濾出一個JavaScript對象。我有一個看起來像這樣的結構:如何過濾兩個日期之間的對象數組?

Object { version: "3.1.1", released_on: "2016-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 } 

我想找到所有的對象從10歲所以"2016-08-21T00:00:00.000Z"之間"2010-08-21T00:00:00.000Z"我遇到的問題是,released_on:領域是一個字符串不是日期。我需要創建一個new Date()對象將其轉換爲字符串,然後使用.filter或者我會做相反的事情,將字符串轉換爲日期然後過濾。有沒有人嘗試過這樣的事情?

+1

'新的Date()。的getTime()'會給你一個數字,將是更容易 –

+0

工作把這個瀏覽器控制檯'的console.log(新的日期(「2016 -08-21T00:00:00.000Z「))''會看到你的日期字符串是完全有效的。甚至可以直接在日期對象上使用比較運算符 – charlietfl

回答

1

您可能會這樣做;

var data = [{ version: "3.1.1", released_on: "2016-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 }, 
 
      { version: "3.1.1", released_on: "2011-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 }, 
 
      { version: "3.1.1", released_on: "2009-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 }, 
 
      { version: "3.1.1", released_on: "2006-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 }, 
 
      { version: "3.1.1", released_on: "2013-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 }, 
 
      { version: "3.1.1", released_on: "2017-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 }, 
 
      { version: "3.1.1", released_on: "2015-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 }, 
 
      ], 
 
     ed = new Date("2016-08-21T00:00:00.000Z").getTime(), 
 
     sd = new Date("2010-08-21T00:00:00.000Z").getTime(), 
 
    result = data.filter(d => {var time = new Date(d.released_on).getTime(); 
 
          return (sd < time && time < ed); 
 
          }); 
 
console.log(result);

相關問題