0

These two version isn't 100% the same, when value is null the result is different:

// version 1
const dogs = animal.dogs || [];
const cats = animal.cats || [];

// version 2
const { dogs = [], cats = [] } = animal;

Since version 1 is a lot tedious, so I want to know is there any concise way to archive this effect.


To be more specific, assumming that animal comes from api, and its value could be animal: { dogs: ['some kind of dog'], cats: ['some kind of cat'] } or animal: { dogs: null, cats: null }

I want to assign value [] to dog or cat when its value is null

  • 2
    Does this answer your question? [How to destructure nested object with null value using default value](https://stackoverflow.com/questions/56108874/how-to-destructure-nested-object-with-null-value-using-default-value) – evolutionxbox Dec 21 '20 at 13:21
  • If there is no new way around in the four years (which I could not find), the accepted answer to this question tells there's no shortcut: https://stackoverflow.com/q/39522014/4636715 – vahdet Dec 21 '20 at 13:22
  • Do you want the value to be null or [] ? Do these snippets help? https://stackoverflow.com/a/48433029/3825777 or this? https://stackoverflow.com/a/45210379/3825777 or this? https://stackoverflow.com/questions/45105782/javascript-array-destructuring-assignment-and-null-value – react_or_angluar Dec 22 '20 at 04:16

0 Answers0