-1

I would like to conditionally add an attribute to an object. Currently I have this:

    const obj = {
    name: car.name,
    battery: car.battery && car.battery, 
    fuel: car.fuel && car.fuel
}

The problem is that if car.battery is not present I have battery: undefined. I would rather prefer not having that attribute in the object if it is not present. How can I achieve that?

baao
  • 71,625
  • 17
  • 143
  • 203
andreaspfr
  • 2,298
  • 5
  • 42
  • 51
  • `if (car.battery) obj.battery = car.battery;`… – deceze Dec 06 '17 at 09:17
  • 3
    Though, really… what are you doing here? You're just making a copy of the `car` object in a really verbose way. – deceze Dec 06 '17 at 09:18
  • If you want to solve this inline, you can use `battery: car.battery || 'something else if falsy'`. Beware though, that if `car.battery` is `0`, you will get `'something else if falsy'` – JanS Dec 06 '17 at 09:19

1 Answers1

2

The problem is that if car.battery is not present I have battery: undefined. I would rather prefer not having that attribute in the object if it is not present.

Simply

const obj = Object.assign({}, car);

If car doesn't have battery or fuel, it won't get copied to obj

gurvinder372
  • 66,980
  • 10
  • 72
  • 94