简体   繁体   中英

Traverse nested object and change values

I've got an object containing user-data alongside some dates. I'd like to format these dates (as they are delivered like this 2015-02-13T18:25:37+01:00 ).

I'd like to have the values of the object changed in-place but how can I do this?

I traverse the object like this:

$.each(myObject, formatDates)
    var isDate = function(value) {
        return  (value!==null && !isNaN(new Date(value)))
    }

    var formatDates = function(key, value){
        if (isDate(value)) {
            // Change value here
            console.log("key:" + key + " value: " + value)
        }

        // Recursive into child objects
        if (value !== null && typeof value === "object") {
            $.each(value, formatDates)
        }
    }

You can use this

function iterate(obj) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                    iterate(obj[property]);
                } else {
                  // do your date thing
                }
            }
        }
        return obj;
    }

iterate(object)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM