2016-08-24 187 views
3

我有以下類型的對象:如何使用lodash更改深層嵌套對象中的對象鍵?

{ 
    options: [ 
    { id: 1, value: 'a' } 
    ], 
    nestedObj: { 
    options: [ 
     { id: 2, value: 'b' } 
    ] 
    } 
} 

如何更改鍵「id」兩個,選擇數組中的第一級和嵌套的水平?我曾嘗試使用lodash這個而不是一直能得到期望的結果:

{ 
    options: [ 
    { newKey: 1, value: 'a' 
    ], 
    nestedObj: { 
    options: [ 
     { newKey: 2, value: 'b' } 
    ] 
    } 
} 

所以我想找到它的工作原理是lodash mapKeys但將通過深嵌套的對象迭代函數。

+0

它可以出現在任何深度? – alex

+0

@alex是的,具有這些鍵值對的對象的選項數組可以並將出現在任何深度。 –

回答

4

您可以使用_.transform()遞歸替換鍵:

var obj = { 
 
    options: [{ 
 
    id: 1, 
 
    value: 'a' 
 
    }], 
 
    nestedObj: { 
 
    options: [{ 
 
     id: 2, 
 
     value: 'b' 
 
    }] 
 
    } 
 
}; 
 

 
console.log(replaceKeysDeep(obj, { 
 
    id: 'newKey', 
 
    options: 'items' 
 
})); 
 

 
function replaceKeysDeep(obj, keysMap) { // keysMap = { oldKey1: newKey1, oldKey2: newKey2, etc... 
 
    return _.transform(obj, function(result, value, key) { // transform to a new object 
 

 
    var currentKey = keysMap[key] || key; // if the key is in keysMap use the replacement, if not use the original key 
 

 
    result[currentKey] = _.isObject(value) ? replaceKeysDeep(value, keysMap) : value; // if the key is an object run it through the inner function - replaceKeys 
 
    }); 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>