![](/img/trans.png)
[英]How to deeply map object keys with JavaScript (lodash)?
[英]How to change object keys in deeply nested object with 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一样工作的函数,但会遍历深层嵌套对象。
您可以递归使用_.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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.