schoenbl
schoenbl

Reputation: 723

Cannot get mapped map to return value

I can't figure out why this is returning undefined:

filterComms = (cards) => {
                    emptyArray = []
                    emptyArray[0] = cards
                    // console.log('emptyArray', emptyArray)
                    emptyArray.map(
                        (v, i) => {
                            return(
                                v.comment.map(
                                    (c, i) => {
                                        if (c.parent_comment_id === null) {
                                            console.log(c) 
                                            return c
                                        }
                                    }
                                )
                            )
                        }
                    )
                }

When I console.log c, I receive the correct value.

This is what the data looks like that I've fed in: https://codepen.io/schoenbl/pen/JgdOQN?editors=0010

Upvotes: 0

Views: 37

Answers (1)

Jack Bashford
Jack Bashford

Reputation: 44087

You're not returning the mapped value - in fact, because you aren't assigning anything to the new array returned from map (it doesn't mutate the original array), that entire map function is useless because the result isn't being assigned to anything, as such it's being garbage-collected. The simplest fix is to return the map.

return emptyArray.map(...);

If you were trying to use the ES6 implicit return in arrow functions, that requires the first non-whitespace character after the fat arrow => to not be an opening curly brace {. Your function can easily be simplified like so, especially because you're basically making a new array - you don't even need the emptyArray variable. You can also mix in some destructuring to only get the wanted properties back:

filterComms = cards => [cards].map(({ comment }) => comment.map(({ parent_comment_id, ...c }) => parent_comment_id === null ? { ...c, parent_comment_id } : undefined));

Upvotes: 3

Related Questions