1

updated_atキーを使用し、のcreated_atような文字列タイムスタンプを持つオブジェクトがあります2012-08-29T16:04:34-04:00。これをMongoDBに挿入しています。updated_atキャッチは、各オブジェクトがとのインスタンスを可変数持つことができることですcreated_at(それらは内の配列にあります)。配列を検索して値を次のように置き換えるためupdated_atに使用できるコードはありますか?created_at$.created_at = new Date($.created_at)

{
    "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"),
        },
    ]
}
4

2 に答える 2

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)
于 2012-08-29T20:49:50.530 に答える
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 ...-操作の結果を格納するには、変更行を次のように調整する必要があります...

x.logs[y].created_at = new Date( x.logs[y].created_at )
于 2012-08-29T20:36:23.753 に答える