Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional spread element

const cond = false  const extraInfo = [   {     a: 11,     b: 25   },   {     a: 12,     b: 34   },   {     a: 1,     c: 99   } ]  const userInfo = [   {     z: 8   },   {     z: 10   },   ...(cond && extraInfo) ] 

When cond is true, I want both extra and user info.

When cond is false, only userInfo is needed.

The issue is when cond is false, I get

TypeError: (intermediate value)(intermediate value)(intermediate value)[Symbol.iterator] is not a function

My understanding is that I am not allowed to use a boolean as a spread element, in this case ...false.

But ...( cond ? extraInfo : {} ) doesn't seem to work either.

What is going on?

like image 444
Liren Yeo Avatar asked Dec 19 '17 08:12

Liren Yeo


People also ask

What happens if you spread an empty array?

Spreading into an Array We need an empty array at end because we cannot spread undefined or null into an array (they are not iterables). Spreading an empty array into another just keeps the array intact.

What is spread operator with example?

The spread operator allows you to spread out elements of an iterable object such as an array, map, or set. For example: const odd = [1,3,5]; const combined = [2,4,6, ...odd]; console.log(combined); Code language: JavaScript (javascript)

Can I use spread for object?

Spread syntax can be used when all elements from an object or array need to be included in a new array or object, or should be applied one-by-one in a function call's arguments list.


2 Answers

Just make it

...(cond ? extraInfo : []) 

Demo with true

var cond = true;    var extraInfo = [    {      a: 11,      b: 25    },    {      a: 12,      b: 34    },    {      a: 1,      c: 99    }  ];    var userInfo = [    {      z: 8    },    {      z: 10    },    ...(cond ? extraInfo : [])  ];    console.log( userInfo );

Demo with false

var cond = false;    var extraInfo = [    {      a: 11,      b: 25    },    {      a: 12,      b: 34    },    {      a: 1,      c: 99    }  ];    var userInfo = [    {      z: 8    },    {      z: 10    },    ...(cond ? extraInfo : [])  ];    console.log( userInfo );
like image 60
gurvinder372 Avatar answered Oct 02 '22 21:10

gurvinder372


Conditionally spread an entity to Object

console.log(   {      name: 'Alex',     age: 19,     ...(true && { city: 'Kyiv' }),     ...(false && { country: 'Ukraine' })   } )   // { name: 'Alex', age: 19, city: 'Kyiv' }  

Conditionally spread an entity to Array

 console.log(   [     'Dan',     'Alex',     ...(true ? ['Robin'] : [])   ] )  // [ 'Dan', 'Alex', 'Robin' ]  
like image 31
Purkhalo Alex Avatar answered Oct 02 '22 22:10

Purkhalo Alex