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