我有以下类型的对象:
{
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 :(得分:13)
您可以递归使用_.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>
&#13;