[英]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
). 我想格式化这些日期(因为它们像
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.