I have a following kind of object:
{
options: [
{ id: 1, value: 'a' }
],
nestedObj: {
options: [
{ id: 2, value: 'b' }
]
}
}
How do I change the key 'id' on both, options array in first level and in the nested level? I have tried to use lodash for this but not have been able to get the desired result:
{
options: [
{ newKey: 1, value: 'a'
],
nestedObj: {
options: [
{ newKey: 2, value: 'b' }
]
}
}
So I would like to find a function which works like lodash mapKeys but would iterate through deep nested object.
renameKeys() Method. The Lodash _. renameKeys() method takes an object and a mapping object and returns a new object where the keys of the given object have been renamed as the corresponding value in the keyMap.
You can access the nested object using indexes 0, 1, 2, etc. So data[0]. alt[0] will access the first alt nested object. Now you can call the above mentioned keys() function to get a list of its keys.
Using Spread Operator assign and the spread operator just shallow-merge the objects. To fix this and correctly merge two deeply nested objects, we can use the merge method provided by the Lodash library.
You can use _.transform()
recursively to replace keys:
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With