Home > Mobile >  JS: conditionally adding adding in the middle of an array?
JS: conditionally adding adding in the middle of an array?

Time:12-17

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.

CodePudding user response:

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

CodePudding user response:

You can use a spread operator:

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

const data = [
   {
     name: "dog",
     age: 11
   }, 
   ...(foo ? [animal] : null),
   {
     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.


Bonus

This example could be simplified further (assuming that foo is a boolean):

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

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

console.log(data);

In this example we're leveraging the properties of the && operator, which returns the right operand if the left operand is truthy, or the left operand if it's falsy (in this case spreading a boolean into an array will have the same effect as spreading a null).

CodePudding user response:

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

  • Related