JavaScriptでPunkのfunc.reduce ()
6573 ワード
Implement a simple pluck using Array.prototype.reduce.
配列を提供する
const pluck = (list, key) =>
list.reduce((pV, cV) => (key in cV ? [...pV, cV[key]] : [...pV]), []);
用途
配列を提供する
list
) オブジェクトとプロパティ名key
) をクリックすると、関数はlist[n*][key]
.// Sample data
const movies = [
{
title: "Invasion of the Body Snatchers",
releaseDate: 1978,
mpar: "R",
rating: 5,
comments: "This is my favorite!",
},
{
title: "Invasion of the Body Snatchers",
releaseDate: 1956,
comments:
"This a good film, but doesn't have Jeff Goldblum, Leonard Nimoy, or even Donald Sutherland in it.",
},
{
title: "The Invasion",
releaseDate: 2007,
rating: 3,
comments: "Not my favorite, but it was watchable.",
},
{
title: "Attack the Block",
releaseDate: 2010,
rating: 4.5,
comments: "A fun movie, innit.",
},
{
title: "Ubik",
comments: "It's just as well; they probably would have ruined it anyway.",
mpar: null,
},
];
すべてを摘むtitle
値movies
...console.log(pluck(movies, "title"));
[
'Invasion of the Body Snatchers',
'Invasion of the Body Snatchers',
'The Invasion',
'Attack the Block',
'Ubik'
]
すべてを摘むmpar
からの映画協会協会movies
.console.log(pluck(movies, "mpar"));
[ 'R', null ]
注意pluck()
Falsie値によってだまされないので(key in cV)
明示的にキーをチェックし、値が何であってもundefined
! 私は、これがあなたが望むものであると思いますpluck()
それを一般的に保つために.あなたのような不要な値を消去することができますundefined
or false
の後にフィルタリングコールバックを受信するために(key in cV)
, しかし、私は愚かであるので、私はそれを単純にしています.Reference
この問題について(JavaScriptでPunkのfunc.reduce ()), 我々は、より多くの情報をここで見つけました https://dev.to/365erik/pluck-func-in-javascript-with-reduce-2od5テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol