Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding value to array if condition is fulfilled

I am building an array of hashes of arrays

my @array = (
    {label => 'first hash'},
    {label => 'second hash',
     innerarray => [
        {label => 'first inner hash'},
        {label => 'second inner hash'},
      ]
    },
);

Is there a way to only add the second inner hash only if a condition is fullfilled? Something like this:

my @array = (
    {label => 'first hash'},
    {label => 'second hash',
     innerarray => [
        {label => 'first inner hash'},
        {label => 'second inner hash'} if 1==1,
      ]
    },
);

I tried to rewrite my code using push:

my @innerarray = ();
push @innerarray, {label => 'first inner hash'};
push @innerarray, {label => 'second inner hash'} if 1==1;

my @array = (
    {label => 'first hash'},
    {label => 'second hash',
     innerarray => \@innerarray
    },
);

But it becomes very illegible, as I have to predefine all inner array before using them, which in some cases is several 100 lines of code above the usage.

Is there any way to add the if-condition directly where I insert the array-element?

like image 712
Pit Avatar asked May 02 '12 13:05

Pit


People also ask

How do you add an object to an array based on condition?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.

Can you add value to array?

When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().

How do you define an array with conditional elements?

The simplest and most obvious way is to define the array with all the required elements, and then conditionally call push . const myArray = ['a', 'b', 'c', 'd']; condition && myArray.

How do I find the first element of an array by address?

An array object starts with its first element so the address of the first element of an array will have the same value as the address of the array itself although the expressions &a[0] and &a have different types.


1 Answers

Use the conditional operator, it is usable as expression.

my @array = (
    {label => 'first hash'},
    {
        label      => 'second hash',
        innerarray => [
            {label => 'first inner hash'},
            (1 == 1)
                ? {label => 'second inner hash'}
                : (),
        ]
    },
);
like image 144
daxim Avatar answered Nov 09 '22 00:11

daxim