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?
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 );
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' ]
let getMyValue = cond ? [].concat(extraInfo, userInfo) : userInfo;
let check this
const extraInfo = [
{
a: 11,
b: 25
},
{
a: 12,
b: 34
},
{
a: 1,
c: 99
}
];
const userInfo = [
{
z: 8
},
{
z: 10
},
];
const cond = false;
let getMyValue = cond ? [].concat(extraInfo, userInfo) : userInfo;
console.log(getMyValue)