Let's assume that we have the following object:
jsxconst forum = { post_1: { message: 'Hi', user: 'Erik' }, post_2: { message: 'Bye', user: 'Erik', replies: { reply_1: { message: 'Bye', user: 'Tim' } } } }
If we wanted to get an array with the replies on each post, our first approach could be:
jsx// Getting posts let posts = Object.values(forum); // Getting posts with replies // 🔴 This returns an error. Cannot convert undefined or null to object let replies = posts.map(post => Object.values(post.replies));
This option returns an error because there isn't a replies
object in post_1
.
Check if the post has replies:
jsxlet replies = Object.values(forum).map(post => post.replies ? Object.values(post.replies) : ['No replies']);
Use destructuring and assign an inital value to the replies
object:
jsxlet replies = Object.values(forum).map( ({ replies = {default: 'No replies'} }) => Object.values(replies));
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.