Ramda 之 pluck()

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

内容简介:實務上我們有時會想將 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()


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

查看所有标签

猜你喜欢:

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

Programming the Mobile Web

Programming the Mobile Web

Maximiliano Firtman / O'Reilly Media / 2010-07-23 / $44.99

* Learn how to use your existing skills to move into mobile web development * Discover the new possibilities of mobile web development, and understand its limitations * Get detailed coverage of ......一起来看看 《Programming the Mobile Web》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具