Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Graph traversal javascript with update convert date
// The object graph
let date = new Date()
let data = {
result: {
id: 'query1',
list: [1, 'hello', date],
hash: {hello: 1, bye: 2, z: 'hello', d: date},
goal: 50,
created_at: date
}
}
// Setting up realistic data
data = JSON.stringify(data)
data = JSON.parse(data)
// The date format from (new Date()).toString()
const format = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/
// The converter
const convert = (val) => {
// Convert
if (format.test(val)) {
return new Date(val)
}
return val
}
// Traverse
const traverse = (obj) => {
for (let k in obj) {
if (obj[k] && typeof obj[k] === 'object') {
traverse(obj[k])
} else {
// Do something with obj[k]
obj[k] = convert(obj[k])
}
}
}
// Start traversing
traverse(data)
console.log(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.