farm command
farm command

Reputation: 693

how to add something to an object if it doesn't have it already

Dealing with ES6, I have an object and I need to add something to it if it already doesn't have it, so below is my work:

const a = {name:"haha",address:"here",rate:6};
const b = {rate:3,...a};

so if object a has that rate it will remain but if it doesn't have it, rate:3 will be added to the object. BUT, I remember that we could do it with || operator (or &&, I don't remember which operator). could you tell me how it was done that way?

Upvotes: 0

Views: 106

Answers (4)

SrThompson
SrThompson

Reputation: 5748

The "old" way to do it would be:

b.rate = a.rate || 3; // This would fail if a.rate === 0
b.rate = a.rate === undefined ? 3 : a.rate; // This would fail if a.rate === null
b.rate = a.rate === undefined || a.rate === null ? 3 : a.rate;

You could also use Object.assign to simulate object-spread:

const b = Object.assign({rate: 3}, a);

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370989

Before object spread was usable, you could use:

const a = {name:"haha",address:"here",rate:6};
const b = Object.assign({}, a, { rate: a.rate || 3 });
console.log(b);

But this may not work as intended, because using || relies on the preceding expression being truthy. If a.rate is falsey but still defined, like the empty string or 0, then it will be overwritten, so it may be better to avoid || and explicitly check for whether a.rate is defined or not, which can be put into the rate property concisely with the conditional operator:

const a = {name:"haha",address:"here",rate:6};
const b = Object.assign({}, a, {
  rate: a.rate === undefined ? 3 : a.rate
});
console.log(b);

Upvotes: 0

Ele
Ele

Reputation: 33726

Use the keyword in to check if the property exists

b.rate = 'rate' in b ? a.rate : 3;

Upvotes: 4

sofcal
sofcal

Reputation: 490

You can initialize a value with || by using:

const val = something || somethingElse;

However, this doesn't work as well when using it for objects. E.g

const obj1 = { rate: 1 };
obj1.rate = obj1.rate || 1; // this is fine
obj1.rate = obj1.rate || obj2.rate; // if obj1.rate and obj2.rate do not exist, obj1.rate will be set to undefined. But that's not always what you want. If you don't want rate set at all, this would be an unexpected result

Upvotes: 0

Related Questions