Recursion over a Tree structure

node v12.22.12
version: master
endpointsharetweet
Runkit to support YouTube video https://www.youtube.com/watch?v=uaLDj8uyXi0
const rxIsoDate = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/ const isIsoDate = value => typeof value === 'string' && rxIsoDate.test(value) const raw = { a: 1, date: '2020-07-17T01:32:26.206Z', second: { b: 2, createdAt: '2020-07-17T01:32:26.206Z', third: { c: 3, updatedAt: '2020-07-17T01:32:26.206Z' } } } const toJsDate = obj => { if (isIsoDate(obj)) return new Date(obj) if (typeof obj !== 'object') return obj const nextObj = {} for (const [prop, value] of Object.entries(obj)) { nextObj[prop] = toJsDate(value) } return nextObj } toJsDate(raw)
As a bonus, I'll change the for loop to use reduce:
const toJsDateReduce = obj => { if (isIsoDate(obj)) return new Date(obj) if (typeof obj !== 'object') return obj return Object.entries(obj).reduce( (nextObj, [prop, value]) => Object.assign(nextObj, { [prop]: toJsDate(value) }), {} ) } toJsDateReduce(raw)
Another example using Object.entries and Object.fromEntries.
const toJsDateEntries = obj => { if (isIsoDate(obj)) return new Date(obj) if (typeof obj !== 'object') return obj const entries = Object.entries(obj).map(([prop, value]) => [prop, toJsDate(value)]) return Object.fromEntries(entries) } toJsDateEntries(raw)
Loading…

1 comment

  • posted 4 years ago by johnsw
    Thanks for the article Joel. Just to alert you to a couple of errors in your bonus code. runkit appears to give correct results because you are calling toJsDate on line 38 and not toJsDateReduce. Then on line 34 you need to recurse by calling toJsDateReduce and NOT toJsDate. Finally, the initial iteration of reduce needs an empty object {} for its accumulator. I think it should be: const toJsDateReduce = obj => { if (isIsoDate(obj)) return new Date(obj) if (typeof obj !== 'object') return obj return Object.entries(obj).reduce((nextObj, [prop, value]) => Object.assign(nextObj, { [prop]: toJsDateReduce(value) }), {} ) } toJsDateReduce(raw) Cheers Joel. Really appreciate the minute JS series you are doing. I've learnt a lot from you over the past few year on medium, etc. Please keep teachin

sign in to comment