-1

Do you know is there a way of null guarding a destructure that happens inside a map?

For example, if my array's first element's age is null then is there a way of writing it so that it doesn't crash when iterating over the destructured values?

export function Component(array) {
  return (
    <>
      {array.map(({ name, age }) => (
        <>
          <div>{name}</div>
          <div>{age}</div>
        </>
      ))}
    </>
  )
}

I know with destructuring you can use this pattern to allow the assignment of null values be assigned and not crash

const {name, age} = {...array}

Is it possible to do a similar thing inside the map?

kind user
  • 40,029
  • 7
  • 67
  • 77
pyan
  • 865
  • 2
  • 12
  • 23
  • 1
    What do you think `const {name, age} = {...array}` does? Why not set defaults directly? `({ name = '', age = 0 } = {})`? – evolutionxbox Sep 27 '22 at 11:48
  • If an element in `array` could be `null` (or `undefined`) , don't use destructuring in the map function argument, use simply the element, check for "truthyniess", and then just use `element.name` and `element.age` in your rendering. – tromgy Sep 27 '22 at 11:50
  • When you say `null` do you mean the value of `age` is `null` or the `age` property is missing from the object? Having a `null` value won't crash the app and, having just tested it, neither would having a missing `age` property. – Andy Sep 27 '22 at 12:14

1 Answers1

0

If one the values of the array element (name or age) are null,or both of them, you will not have errors, just an empty div. If you expect an element that is null itself, then you can filter the array first for those elements, like so:

array.filter((el) => Boolean(el)).map(({ name, age }) => ...)
FlushBG
  • 183
  • 1
  • 10