Using Ramda.js Lenses
Ramda offers a SUPER nice API to augment data and maintain immutability.
Basic usage
R.over()
takes a path array, function to apply and data to augment
// Our initial object
const user = { firstname: "miceal", lastname: "gallagher" };
// The path to the data attribute
const lensPath = ["firstname"];
// The function to augment data
const setFirstname = () => "Mehaul";
// Putting it all together
R.over(lensPath, setFirstname, user);
// { firstname: "Mehaul", lastname: "gallagher" };
Deeply nested object attribute
You can specify an array index in a path.
const user = {
emails: [
{
email: "user@domain.com",
isPrimary: true
}
]
}
const lensPath = ["emails", 0, "email"];
const toUpperCase = (name) => name.toUpperCase()
// Putting it all together
R.over(lensPath, toUpperCase, person);
/*
{
emails: [
{
email: "USER@DOMAIN.COM",
isPrimary: true
}
]
}
*/
Modifying object collections
Use Ramda’s map()
and lense over an object collection
// Putting it all together
R.over(lensPath, R.map(toUpperCase), user);
/*
...
emails: [
{
email: "USER@DOMAIN.COM",
},{
email: "USER@DOMAIN.COM",
}
]
}
*/
Conclusion
R.over
offers immutability, returning a new value after a lense is applied. Currying in Ramda allows function composition that can aid in code readability.