有没有一种方法可以更有效地执行以下操作?
(我使用 CoffeeScript ,所以也许还有 CoffeeScript 特定的解决方案?..)
oldObj =
parent:
child:
grandchild: "I'm a grandchild!"
newObj =
parent:
child:
grandchild: null
newObj.parent.child.grandchild = oldObj.parent.child.grandchild
我不能简单地执行 newObj.parent = oldObj.parent
因为 oldObj.parent
可能包含 anotherChild
和 yetAnotherChild
> 等等 - 我不知道它还包含什么(也不想知道),我只需要 child
。
最佳答案
您可以创建通用递归函数来向对象添加属性
oldObj =
parent:
child:
grandchild: "I'm a grandchild!"
addPropertyToObject = (obj, property, valueProperty) ->
if typeof property == 'string'
property = property.split(".")
obj[property[0]] = obj[property[0]] || {}
tmpObj = obj[property[0]]
if property.length > 1
property.shift()
addPropertyToObject tmpObj, property, valueProperty
else
obj[property[0]] = valueProperty
obj
newObj = addPropertyToObject {}, "parent.child.grandchild", oldObj.parent.child.grandchild
关于javascript - 将对象的孙子属性复制到新创建的对象,无需太多代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35338813/