Ramda 之 pluck()

栏目: JavaScript · 发布时间: 7年前

内容简介:實務上我們有時會想將 Array 中 Object 的某個 Property 取出其 Value 成為新的 Array,但不希望有 Object 與 Key,此時可使用 Ramda 的VS Code 1.31.1Quokka 1.0.136

實務上我們有時會想將 Array 中 Object 的某個 Property 取出其 Value 成為新的 Array,但不希望有 Object 與 Key,此時可使用 Ramda 的 pluck() 大幅簡化程式碼。

Version

VS Code 1.31.1

Quokka 1.0.136

Ramda 0.26.1

map()

import { map } from 'ramda';

const data = [
  { id: 1, title: 'FP in JavaScript' },
  { id: 2, title: 'RxJS in Action' },
  { id: 3, title: 'Speaking JavaScript' }
];

const getBooks = map(x => x.title);
console.dir(getBooks(data));

希望只取出 title 的 value 成為新的 array,不想要 object 與 key,可直接使用 map() ,projection function 則使用 arrow function 表示。

map()

(a -> b) -> [a] -> [b]

將 a 格式 array 轉換成 b 格式 array,且筆數不變

Ramda 之 pluck()

prop()

import { map, prop } from 'ramda';

const data = [
  { id: 1, title: 'FP in JavaScript' },
  { id: 2, title: 'RxJS in Action' },
  { id: 3, title: 'Speaking JavaScript' }
];

const getBooks = map(prop('title'));
console.dir(getBooks(data));

若想讓 map() 的 projection function 也 Proint-free,可使用 Ramda 的 prop() 產生。

prop()

s -> {s: a} -> a | undefined

傳入 key 與 object,傳回 value

Ramda 之 pluck()

pluck()

import { pluck } from 'ramda';

const data = [
  { id: 1, title: 'FP in JavaScript' },
  { id: 2, title: 'RxJS in Action' },
  { id: 3, title: 'Speaking JavaScript' }
];

const getBooks = pluck('title');
console.dir(getBooks(data));

map()prop() 可簡化成 pluck()

pluck()

Functor f => k → f {k: v} → f v

將 array 中特定 property 的 value 取出,成為新的 array

k :object 的 key

f {k: v} : Functor 內為 object

f v : Functor 內為 value

Ramda 之 pluck()

Conclusion

  • 若對 pluck() 定義中的 functor 不清楚,可先想成 array 即可
  • pluck() 相當於 map(prop(k), f) ,其中 f 為 functor

Reference

Ramda , map()

Ramda , prop()

Ramda , pluck()


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

High-Performance Compilers for Parallel Computing

High-Performance Compilers for Parallel Computing

Michael Wolfe / Addison-Wesley / 1995-6-16 / USD 117.40

By the author of the classic 1989 monograph, Optimizing Supercompilers for Supercomputers, this book covers the knowledge and skills necessary to build a competitive, advanced compiler for parallel or......一起来看看 《High-Performance Compilers for Parallel Computing》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具