2012-08-29 62 views
1

我有一些對象使用的鍵爲updated_atcreated_at,它們的字符串時間戳記爲2012-08-29T16:04:34-04:00。我將它插入到MongoDB中。捕獲是每個對象可以具有可變數目的實例updated_atcreated_at(它們在數組內)。是否有任何代碼可用於搜索數組updated_atcreated_at並用$.created_at = new Date($.created_at)替換值?插入JSON到MongoDB自動從字符串中轉換日期

{ 
    "name":"thomas", 
    "created_at":"2012-08-29T16:04:34-04:00", 
    "updated_at":"2012-08-29T16:04:34-04:00", 
    "logs":[ 
     { 
      "something":"something", 
      "created_at":"2012-08-29T16:04:34-04:00", 
     }, 
     { 
      "something":"something", 
      "created_at":"2012-08-29T16:04:34-04:00", 
     }, 
    ] 
} 

{ 
    "name":"thomas", 
    "created_at":new Date("2012-08-29T16:04:34-04:00"), 
    "updated_at":new Date("2012-08-29T16:04:34-04:00"), 
    "logs":[ 
     { 
      "something":"something", 
      "created_at":new Date("2012-08-29T16:04:34-04:00"), 
     }, 
     { 
      "something":"something", 
      "created_at":new Date("2012-08-29T16:04:34-04:00"), 
     }, 
    ] 
} 

回答

1
// store your data object in x 
x = { 
    "name":"thomas", 
    "created_at":"2012-08-29T16:04:34-04:00", 
    "updated_at":"2012-08-29T16:04:34-04:00", 
    "logs":[ 
     { 
      "something":"something", 
      "created_at":"2012-08-29T16:04:34-04:00", 
     }, 
     { 
      "something":"something", 
      "created_at":"2012-08-29T16:04:34-04:00", 
     }, 
    ] 
} 

// create a traversal function to recurse 
function traverse(o) { 
    // loop through object 
    for (i in o) { 
     // if it is a matched key (current regex matches created_at or updated_at) 
     // parse the item as a date, and re-store object 
     if(i.match(/(cre|upd)ated_at/)){ 
      o[i] = new Date(o[i]) 
     } 
     // if the key we are looking at is an object, then recurse! 
     if (typeof(o[i])=="object") { 
      traverse(o[i]) 
     } 
    } 
} 

// fire it up! 
traverse(x) 

// check the results 
console.dir(x) 
+0

這太棒了,謝謝。 – ThomasReggi

+0

沒問題 - 這是適應形式另一回答 –

0
// store your data object in x 
x = { 
    "name":"thomas", 
    "created_at":"2012-08-29T16:04:34-04:00", 
    "updated_at":"2012-08-29T16:04:34-04:00", 
    "logs":[ 
     { 
      "something":"something", 
      "created_at":"2012-08-29T16:04:34-04:00", 
     }, 
     { 
      "something":"something", 
      "created_at":"2012-08-29T16:04:34-04:00", 
     }, 
    ] 
} 

// loop through each element of the logs array 
for(y in x.logs){ 
    // modify the `created_at` value of the y-th element 
    // by wrapping with the desired string 
    x.logs[y].created_at = "new Date(" + x.logs[y].created_at + ")" 
} 

// check the final format of the object 
console.dir(x) 

警告:

對象存儲包含new Date ... ammendment一個字符串 - 用於存儲操作的結果,則需要調整修改線...

x.logs[y].created_at = new Date(x.logs[y].created_at) 
+0

這不會得到'x.created_at'和'x.updated_at'。這只是一個簡單的例子,真正的例子有更多的嵌套選項。我想要更多以搜索爲導向的東西。假設你有一個無限嵌套的對象,並且你想要替換'created_at'和'updated_at'。 – ThomasReggi