Destructuring nested fields in Contentful CMS data, and formatting a date for the blog list
Originally written on
Up until now I was mostly pulling fields from Contentful and passing them through. For the blog index I wanted the post dates to read right for the site language (Serbian) so I needed something like toLocaleDateString('sr-RS') before the data hit the page.
The annoying part isn't the locale, it's where the date actually lives. Entries come back with this nested shape (item.fields.date inside whatever the entries look like), and I can't just tweak one property in place and pretend the rest of the object is unchanged. I had to map over the array, copy the entry, copy fields, and only then replace date with the formatted string while keeping everything else intact - a bit of destructuring/spread gymnastics. Took me a bit of brainwracking before it clicked.
1const newBlogData = res.fields.blog?.map((item) => ({2 ...item,3 fields: {4 ...item.fields,5 date: new Date(item.fields.date).toLocaleDateString('sr-RS'),6 },7}));89return {10 props: { ...res.fields, blog: newBlogData },11};12
Nothing revolutionary, but it's a good little drill for a slightly fussy nested structure, and I'm writing it down as a reminder for the future.