12

I have an array of objects:

  const arr = [
    {
      name: 'John',
      money: 45
    },
    {
      name: 'Lui',
      money: 65
    },
    {
      name: 'Kegan',
      money: 100
    },
    ... isNewUser  ? {
      name: 'Eric',
      money: 90
    } : {}
  ]

I need to conditionally add the object when it is declared not using array.push. I've tried using the && operator but I just got errors.isNewUser is a boolean variable and if true, array should have 4 items, else the array should only have 3 which doesn't include the newUser object

4
  • Why do you need to do it during initialisation? What is is the problem you're trying to solve? Commented Mar 31, 2021 at 16:55
  • I have a large codebase that contains arrays like this and I now I need to display data conditionally and adding array.push() after every declaration would cause more ugly code. Im trying to keep it as clean as possible Commented Mar 31, 2021 at 16:56
  • 1
    You have a different definition of "clean" then I do... Commented Mar 31, 2021 at 16:57
  • 1
    If it can be solved in one line using a spread operator than adding if(isNewUser) {...} every time it is used would be mmuch simpler and less duplication Commented Mar 31, 2021 at 16:59

5 Answers 5

32

You can only spread an array into an array. So simply make your conditional element an array.

var arr = [{
        name: 'John',
        money: 45
    },
    {
        name: 'Lui',
        money: 65
    },
    {
        name: 'Kegan',
        money: 100
    },
    ...isNewUser ? [{
        name: 'Eric',
        money: 90
    }] : []
]

Anyways, array.push still looks like a better option here!

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

Comments

5

I like Ajith Gopi's answer very much.

I would additionally use some helper functions.

function toArray(obj) {
  if (obj == null) {
    return []
  }
  else if (Array.isArray(obj)) {
    return obj
  }
  else {
    return [obj]
  }
}

function iif(condition, trueObj, falseObj) {
  return condition ? toArray(trueObj) : toArray(falseObj)
}

var arr = [
  {
    name: 'John',
    money: 45
  },
  {
    name: 'Lui',
    money: 65
  },
  {
    name: 'Kegan',
    money: 100
  },
  ...iif(isNewUser, {
    name: 'Eric',
    money: 90
  })
]

Comments

1
let arr = [
    {
      name: 'John',
      money: 45
    },
    {
      name: 'Lui',
      money: 65
    },
    {
      name: 'Kegan',
      money: 100
    },
   ]
 const newObj = {
      name: 'Eric',
      money: 90
    }

  if(newUser){
   arr = [...arr, newObj];
  }

Comments

0

I really like this question, and this is what i did in the end.

const iif = (cond, obj) => (cond ? [obj] : []);

To use it,

[    
    ...iif(true, ['new item']),
]

Keep in mind, the new item can be very complex object as well.

Comments

-1

Instead of && operator, you can use directly construct the array based on the condition. Please try to like this:

let isNewUser = false;

const arrTest1 = [
      {
        name: 'John',
        money: 45
      },
      {
        name: 'Lui',
        money: 65
      },
      {
        name: 'Kegan',
        money: 100
      },
      ...(isNewUser ? [{
        name: 'Eric',
        money: 90
      }] : [])
    ];
console.log("Test case when isNewUser is false")    
console.log(arrTest1)
console.log("=======================================")
isNewUser = true;

const arrTest2 = [
      {
        name: 'John',
        money: 45
      },
      {
        name: 'Lui',
        money: 65
      },
      {
        name: 'Kegan',
        money: 100
      },
      ...(isNewUser ? [{
        name: 'Eric',
        money: 90
      }] : [])
    ];
    
console.log(arrTest2)

Hope your good luck!

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.