内容简介:對於前端而言 Array 比較好用,適合 HTML Template 做VS Code 1.35.1Quokka 1.0.227
對於前端而言 Array 比較好用,適合 HTML Template 做 v-for ,但有時 API 回傳是 Object,不方便使用,此時前端就得自己轉成 Array。Ramda 的 key() 提供將 Object 的 Key 轉成 Array。
Version
VS Code 1.35.1
Quokka 1.0.227
Ramda 0.26.1
Imperative
let data = {
001: 100,
002: 200,
003: 300,
};
let lut = {
001: 'FP in JavaScript',
002: 'RxJS in Action',
003: 'Speaking JavaScript'
};
// fn :: {a} -> {b} -> {c}
let fn = lut => obj => {
let result = [];
for(let x in obj) {
result.push({
title: lut[x],
price: obj[x]
})
}
return result;
};
console.dir(fn(lut)(data));
第 1 行
let data = {
001: 100,
002: 200,
003: 300,
};
實際 data 為 object,不是 array,key 部分為 ID ,value 部分為 price 。
第 7 行
let lut = {
001: 'FP in JavaScript',
002: 'RxJS in Action',
003: 'Speaking JavaScript'
};
為 ID 與 title 的 lookup table,也是 object。
[ { title: 'FP in JavaScript', price: 100 },
{ title: 'RxJS in Action', price: 200 },
{ title: 'Speaking JavaScript', price: 300 } ]
我們希望結果為 array,其 element 為 object,且根據 lut 顯示對應的 title 與 price 。
13 行
// fn :: {a} -> {b} -> {c}
let fn = lut => obj => {
let result = [];
for(let x in obj) {
result.push({
title: lut[x],
price: obj[x]
})
}
return result;
};
由於結果為 array,imperative 會先建立 result array,使用 for in loop 讀取所有 obj 的 property,重新建立 object push 進 result array。
Functional
import { pipe, keys, map } from 'ramda';
let data = {
001: 100,
002: 200,
003: 300,
};
let lut = {
001: 'FP in JavaScript',
002: 'RxJS in Action',
003: 'Speaking JavaScript'
};
// fn :: {a} -> {b} -> {c}
let fn = lut => obj => pipe(
keys,
map(x => ({ title: lut[x], price: obj[x] })),
)(obj);
console.dir(fn(lut)(data));
以 Functional 角度思考:
keys() map()
Point-free
import { pipe, keys, map, applySpec, prop, __ } from 'ramda';
let data = {
001: 100,
002: 200,
003: 300,
};
let lut = {
001: 'FP in JavaScript',
002: 'RxJS in Action',
003: 'Speaking JavaScript'
};
// fn :: {a} -> {b} -> {c}
let fn = lut => obj => pipe(
keys,
map(applySpec({
title: prop(__, lut),
price: prop(__, obj)
}))
)(obj);
console.dir(fn(lut)(data));
map() 的 callback 可使用 applySpec() 使其 point-free。
Conclusion
- 當 data 為 object,而我們期望為 array 時,可先用
keys()轉成 array,再用map()轉成我們要的格式
Reference
以上所述就是小编给大家介绍的《使用 keys() 將 Object 轉成 Array》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- RecyclerView使用指南(一)—— 基本使用
- 如何使用Meteorjs使用URL参数
- 使用 defer 还是不使用 defer?
- 使用 Typescript 加强 Vuex 使用体验
- [译] 何时使用 Rust?何时使用 Go?
- UDP协议的正确使用场合(谨慎使用)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Rapid Web Applications with TurboGears
Mark Ramm、Kevin Dangoor、Gigi Sayfan / Prentice Hall PTR / 2006-11-07 / USD 44.99
"Dear PHP, It's over between us. You can keep the kitchen sink, but I want my MVC. With TurboGears, I was able to shed the most heinous FileMaker Pro legacy 'solu-tion' imaginable. It has relationshi......一起来看看 《Rapid Web Applications with TurboGears》 这本书的介绍吧!