Prevent Object.values() of 'undefined' in JavaScript

Let's assume that we have the following object:

jsx
const 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.

Solution 1: ternary operator

Check if the post has replies:

jsx
let replies = Object.values(forum).map(post => post.replies ? Object.values(post.replies) : ['No replies']);

Solution 2: destructure

Use destructuring and assign an inital value to the replies object:

jsx
let 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.