Reputation: 469
I am using a library called chartjs
to print the graphics on my screen. For that, I am passing an array of objects that should be displayed in this graph. The problem is that I just want that last object to appear if the state
is equal to 'yes
'. If I remove this conditional, the code works perfectly. Any suggestions on how I could solve this problem?
[
{
data1: 'mydata01',
data2: 'mydata02',
},
{
data3: 'mydata03',
data4: 'mydata04',
},
this.state.condition === 'yes' ? (
{
data3: 'mydata03',
data4: 'mydata04',
},
) : 'remove'
]
Upvotes: 2
Views: 2911
Reputation: 41
If you use the characteristics of the spread operator, you can do it like the code below. The spread operator adds nothing if the subsequent value is an empty array.
var condition = 'yes';
var arr = [{
data1: 'mydata01',
data2: 'mydata02',
},
{
data3: 'mydata03',
data4: 'mydata04',
},
...(condition === 'yes' ? (
[{
data3: 'mydata03',
data4: 'mydata04',
}]
) : [])
]
console.log(arr);
Upvotes: 4
Reputation: 640
Use slice(startPosition, length)
const dataToShow = data.slice(0, this.state.condition === 'yes' ? data.length : data.length - 1)
Upvotes: 1
Reputation:
assuming you're using this array somewhere, (we'll call it usage
), your best bet is to split it out:
usage = [
{
data1: 'mydata01',
data2: 'mydata02',
},
{
data3: 'mydata03',
data4: 'mydata04',
}
];
if (this.state.condition === 'yes') {
usage = [
...usage,
{
data3: 'mydata03',
data4: 'mydata04',
}
];
}
reasoning being, if you put your condition inside the array [1, 2, (test ? 3 : null)]
you'll end up with [1, 2, 3]
or [1, 2, null]
and you likely want to avoid the second one as it could break the library you're using.
Upvotes: 1