5

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.

0

3 Answers 3

3

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; }

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

please try with null. and try to spread false ...
@NinaScholz it throws an error, strangely... I removed that example. Thank for pointing it out!
your solution still insert an item, even if null to the array.
You are right, my bad. Fixed it
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.