Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add object to an array while being declared

Tags:

javascript

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

like image 255
ousmane784 Avatar asked Mar 04 '26 04:03

ousmane784


2 Answers

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!

like image 66
Ajith Gopi Avatar answered Mar 05 '26 16:03

Ajith Gopi


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
  })
]
like image 40
Bart Hofland Avatar answered Mar 05 '26 17:03

Bart Hofland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!