[Ramda] Change Object Properties with Ramda Lenses

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Ramda] Change Object Properties with Ramda Lenses相关的知识,希望对你有一定的参考价值。

In this lesson we‘ll learn the basics of using lenses in Ramda and see how they enable you to focus changes on specific properties of an object while keeping your data immutable.

 

what ‘R.lens‘ do is able to get or set prop value but keep the object immutable.

Normally when you two ways to use lens:

1. set up lens: ‘lens‘ + ‘prop‘ + ‘assoc‘;

After set up you can either get value by using ‘R.view‘;

Or change a prop by using ‘R.set‘ or ‘R.over‘.

 

2.  Using ‘lens‘ + ‘prop‘ + ‘assoc‘ is a little bit work to do, there is short syntax to do the same thing: ‘R.lensProp‘.

const R = require(ramda);

const {view, lens, assoc, prop, set, over, lensProp, toUpper} = R;

const person = {
    firstName: Fred,
    lastName: Filntstore
};

/*
* What lens does is modify prop value for a given object
* and keep data immutable.
* */

const firstNameLens = lens(
    prop(firstName),
    assoc(firstName)
);
const viewFirstName = view(firstNameLens);
// const result = viewFirstName(person); // Fred

/** Using R.set **/
const setFirstName = set(firstNameLens);
const updateFirstName = setFirstName(Zhentian);
// const result = updateFirstName(person); // { firstName: ‘Zhentian‘, lastName: ‘Filntstore‘ }

/** Using R.over instead of set **/
const result = over(firstNameLens, toUpper, person);

/** lensProp instead of prop + assoc **/
const lastNameLens = lensProp(lastName);
const result2 = over(lastNameLens, toUpper, person); // { firstName: ‘Fred‘, lastName: ‘FILNTSTORE‘ }
console.log(result);
console.log(result2);

 

以上是关于[Ramda] Change Object Properties with Ramda Lenses的主要内容,如果未能解决你的问题,请参考以下文章

[Ramda] Convert Object Methods into Composable Functions with Ramda

Ramda 的一些API

[Ramda] Pluck & Props: Get the prop(s) from object array

打字稿:如何键入 Ramda R.prop(key) T' 不可分配给类型为 '(s: ) => 的参数

[Ramda] Basic Curry with Ramda

[Ramda] Sort, SortBy, SortWith in Ramda