2013-10-04 87 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執行遞歸,但我幾乎不會說它更優雅或更好。