有人知道一种从新对象上的属性更新对象属性的好方法,但前提是新对象上的那些属性不是未定义的? 我可以这样做(coffeescript):
setProfileData = (data) ->
_profile.talent_id = if data.id then data.id else _profile.talent_id
_profile.is_talent = if data.is_talent then data.is_talent else _profile.is_talent
_profile.is_employer = if data.is_employer then data.is_employer else _profile.is_employer
不过好像有点啰嗦。
此外,data
实际上是一个类(函数),因此 _.extend 并不是真正的选项。
最佳答案
没有 JavaScript 或 CoffeeScript 运算符可以执行此类分配。但是,您可以通过以下方式避免至少一次重复
if data.id then _profile.talent_id = data.id
或
_profile.talent_id = data.id || _profile.talent_id
您也可以使用existential operator (它确实检查未定义
),而不仅仅是错误。
Also the
data
is actually a class (a function), so_.extend
isn't really an option.
extend
在函数对象上也能正常工作。因此,如果您已经在使用下划线或 lodash,那么您绝对应该使用它。
关于javascript - 从新对象的属性更新对象的属性,但前提是新对象的属性不是未定义的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36021279/