1. // shorthand
  2. lensProp('name');
  3. // longhand
  4. lens(prop('name'), assoc('name'));

Ramda’s lensProp and lensIndex are convenience functions. Understanding the longhand version primes us to dive even deeper. (3 min. read)
Ramda的lensProp和lensIndex是方便的函数。了解速记版本使我们能够更深入地潜水(3分钟(阅读)
lensProp and lensIndex are actually built on top of the lower-level lens function.

lensProp和lensIndex实际上构建在较低级别的镜头功能之上。
This

  1. import { lensProp, view } from 'ramda';
  2. const name = lensProp('name');
  3. const result = view(name, { name: 'Bobo' });
  4. console.log({ result });

Is a convenient shorthand for this

  1. import { assoc, lens, prop, view } from 'ramda';
  2. const name = lens(prop('name'), assoc('name'));
  3. const result = view(name, { name: 'Bobo' });
  4. console.log({ result });

See the difference?

  1. // shorthand
  2. lensProp('name');
  3. // longhand
  4. lens(prop('name'), assoc('name'));
  5. //{ result: 'Bobo' }

Why prop() and assoc()? #

Ramda’s prop function lets you get object properties.

  1. import { prop } from 'ramda';
  2. const person = { name: 'Bobo' };
  3. const name = prop('name', person);
  4. console.log({ name });
  5. //{ result: 'Bobo' }

And assoc lets you set them without mutating the original object.

  1. import { assoc } from 'ramda';
  2. const person = { name: 'Bobo' };
  3. const personWithAge = assoc('age', 25, person);
  4. console.log({ person, personWithAge });
  5. //{ person: { name: 'Bobo' },
  6. personWithAge: { name: 'Bobo', age: 25 } }

And since lenses need a getter and a setter to perform their duties, prop and assoc make the perfect combination to immutably handle and change lenses.

  1. import { assoc, lens, prop, set, view } from 'ramda';
  2. const data = { name: 'Bobo' };
  3. const name = lens(prop('name'), assoc('name'));
  4. const original = view(name, data);
  5. const newObj = set(name, 'Another Name', data);
  6. console.log({
  7. original,
  8. newObj
  9. });

https://ramdajs.com/docs/#assoc

Makes a shallow clone of an object, setting or overriding the specified property with the given value. Note that this copies and flattens prototype properties onto the new object as well. All non-primitive properties are copied by reference.
See also dissoc, pick.
对对象进行浅层克隆,使用给定值设置或重写指定属性。请注意,这也会将原型属性复制并展平到新对象上。所有非基本属性都是通过引用复制的。 另请参见dissoc,pick。

  1. R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}

https://ramdajs.com/docs/#pick 挑选

Returns a partial copy of an object containing only the keys specified. If the key does not exist, the property is ignored.
See also omit, props.
返回仅包含指定键的对象的部分副本。如果密钥不存在,则忽略该属性。 另请参见省略,道具。

  1. R.pick(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1, d: 4}
  2. R.pick(['a', 'e', 'f'], {a: 1, b: 2, c: 3, d: 4}); //=> {a: 1}

https://ramdajs.com/docs/#omit 省略

  1. R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}