1

我有使用键updated_at并且created_at具有字符串时间戳的对象,例如2012-08-29T16:04:34-04:00. 我将它插入到 MongoDB 中。关键是每个对象都可以有可变数量的updated_atand实例created_at(它们在数组中)。是否有任何代码可用于搜索数组updated_atcreated_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 回答