2013-10-04 177 views
2

说我有一个对象,它看起来是这样的 -深克隆对象

data = 
    a: 1 
    b: 2 
    c: 
     d: 3 
     e: 4 
     f: 
      g: 4 
      h: 
       i: 9 

我想写这相当基本复制这个对象深深但其最小的10多

更换数的函数
a: 10 
b: 20 
c: 
    d: 30 
    e: 40 
    f: 
     g: 40 
     h: 
      i: 90 

我想用lodash或下划线来写最少量的代码。这是我目前所做的 -

execute = (key) -> 
#console.log typeof key, key 
if typeof key is 'number' 
    return key * 10 

result = {} 
_.forIn key, (value, name) -> 
    result[name] = execute value 
return result 

请建议一些优雅和干净的东西。

更新:

通过lodash LIB会经过我发现了一个更好的办法 -

_.cloneDeep data,(value) -> value * 10 if typeof value is 'number' 
+0

我想要一个更好的解决方案。 – Tushar

回答

0

execute的纯咖啡版本是

foo = (data, out={})-> 
    if typeof data is 'number' 
    return data*10 
    for k of data 
    out[k] = foo(data[k]) 
    return out 
foo(data) 

递归表达就像他们来时那样优雅。你的_.deepClone更紧凑,因为它可以让lo-dash执行递归,但我几乎不会说它更优雅或更好。