Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change object keys in deeply nested object with lodash?

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.

like image 567
Jaakko Karhu Avatar asked Aug 24 '16 12:08

Jaakko Karhu


People also ask

How do I rename a key in object Lodash?

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.

How do you get keys for nested objects?

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.

How to merge 2 nested objects in JavaScript?

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.


1 Answers

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>
like image 126
Ori Drori Avatar answered Oct 06 '22 06:10

Ori Drori