如果没有对象,如何将其添加到对象中

时间:2018-10-26 19:40:34

标签: javascript ecmascript-6

处理ES6时,我有一个对象,如果它还没有对象,我需要添加一些东西,所以下面是我的工作:

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

因此,如果对象a具有该rate,它将保留,但如果没有,则将rate:3添加到该对象。但是,我记得我们可以使用||运算符(或&&,我不记得是哪个运算符)来做到这一点。你能告诉我怎么做吗?

4 个答案:

答案 0 :(得分:4)

使用关键字in检查属性是否存在

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

答案 1 :(得分:1)

“旧”方法是:

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;

您还可以使用Object.assign模拟对象传播:

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

答案 2 :(得分:0)

您可以使用||初始化值。通过使用:

const val = something || somethingElse;

但是,当将它用于对象时,效果不佳。例如

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

答案 3 :(得分:0)

在对象传播可用之前,您可以使用:

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

但这可能无法按预期工作,因为使用||依赖于前面的表达式为 truthy 。如果a.rate是假的但仍被定义(例如空字符串或0),则它将被覆盖,因此最好避免使用||并明确检查{{1} }是否已定义,可以将其与条件运算符一起简洁地放入a.rate属性中:

rate

相关问题