sal3jfc
sal3jfc

Reputation: 777

JS: conditionally adding adding in the middle of an array?

If i have an array of data,

const data = [
   {
     name: "dog",
     age: 11
   }, 
   {
     name: "cat",
     age: 21,
   }
]

I want to add an object in the middle of that if a condition is true:

const shouldAddNewAnimal = true;

const animal = {
   name: "tiger",
   age : 22,
}

How would I write that without an else ?

const data = [
   {
     name: "dog",
     age: 11
   }, 
   foo ? animal : {};
   {
     name: "cat",
     age: 21,
   }
]

above is the only way I can think of writing it but I dont want to insert an empty object in there if the condition is not true.

Upvotes: 4

Views: 1371

Answers (3)

Alex Lomia
Alex Lomia

Reputation: 7235

You can use a spread operator:

const foo = true;
const animal = { name: "mouse", age: 10 };

const data = [
   {
     name: "dog",
     age: 11
   }, 
   ...(foo ? [animal] : []),
   {
     name: "cat",
     age: 21,
   }
]

console.log(data);

This will result in the animal being extracted out of its enclosing array and added to the "outer" array.

In the case of "else" path, spreading the null will result in nothing being added to the "outer" array.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386883

You could spread with arrays, one with the wanted object and the other empty.

const
    shouldAddNewAnimal = true,
    animal = { name: "tiger", age: 22 },
    data = [
        { name: "dog", age: 11 },
        ...(shouldAddNewAnimal ? [animal] : []),
        { name: "cat", age: 21 }
    ];

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Ran Turner
Ran Turner

Reputation: 18156

You may achieve this by adding null's and filtering them out like so using filter

const shouldAddNewAnimal = false;
const animal = {
   name: 'parrot',
   age:12
}

let data = [
   {
     name: "dog",
     age: 11
   }, 
   shouldAddNewAnimal ? animal : null,
   {
     name: "cat",
     age: 21
   }
].filter(item => item !== null);

console.log(data);

const shouldAddNewAnimal = true;
    const animal = {
       name: 'parrot',
       age:12
    }

    let data = [
       {
         name: "dog",
         age: 11
       }, 
       shouldAddNewAnimal ? animal : null,
       {
         name: "cat",
         age: 21
       }
    ].filter(item => item !== null);

    console.log(data);

Upvotes: 0

Related Questions