javascript-lodashHow can I use Lodash to change the key name of an object in JavaScript?
Using Lodash, you can easily change the key name of an object in JavaScript. Lodash provides a _.mapKeys()
function that can be used to map the keys of an object to a new set of keys.
For example, given the following object:
const obj = {
name: 'John',
age: 25
};
You can use _.mapKeys()
to change the key names to firstName
and yearsOld
like this:
const newObj = _.mapKeys(obj, (value, key) => {
return key === 'name' ? 'firstName' : 'yearsOld';
});
console.log(newObj);
// Output: { firstName: 'John', yearsOld: 25 }
The _.mapKeys()
function takes two arguments: the object to map and a function that determines the mapping of each key. In the example above, the function returns firstName
if the key is name
, and yearsOld
otherwise.
Code explanation
const obj = { name: 'John', age: 25 };
: This creates an object with two keys,name
andage
.const newObj = _.mapKeys(obj, (value, key) => { ... });
: This uses Lodash's_.mapKeys()
function to map the keys of the object to a new set of keys.return key === 'name' ? 'firstName' : 'yearsOld';
: This is the function that determines the mapping of each key. It returnsfirstName
if the key isname
, andyearsOld
otherwise.
Here are some relevant links if you need more information:
More of Javascript Lodash
- How do I use Lodash to zip two JavaScript arrays together?
- How do I import the Lodash library into a JavaScript project?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How do I use an online JavaScript compiler with Lodash?
- How can I use Lodash to create a unique array in JavaScript?
- How do I use Lodash in a JavaScript playground?
- How can I use lodash in a JavaScript sandbox?
- How can I use Lodash to compare an array of objects in JavaScript?
- How can I use Lodash to find the unique key of a JavaScript object?
- How can I use Lodash to manipulate JavaScript objects online?
See more codes...