1
私は配列の最小項目を取得するはずの小さなヘルパーを書いています。計算されたプロパティキーを使用してオブジェクト値にアクセス
この関数は、最初のパラメータとしてArray
をとり、オブジェクトプロパティ 'rest'パラメータにアクセスするための「パス」をとります。
例:minItem(stops, 'duration', 'total');
にconsole.log:期待// [object object][duration][total]
:// Number, Which is the value of total
const stops =
[{"transport":"train","departure":"Paris","arrival":"Madrid","duration":
{"h":"03","m":"15","total":195},"cost":160,"discount":0,
"reference":"TPM0315","initialPrice":160},
{"transport":"bus","departure":"Paris","arrival":"Madrid",
"duration":{"h":"06","m":"45","total":405},"cost":30,"discount":25,
"reference":"BPM0645","initialPrice":40},
{"transport":"car","departure":"Paris","arrival":"Madrid","duration":
{"h":"05","m":"45","total":345},"cost":120,"discount":0,
"reference":"CPM0545","initialPrice":120}];
/** @function minItem */
const minItem = (array, ...args) => {
const keys = `['${[...args].join('\'][\'')}']`;
array.reduce((a, b) => {
console.log(b + keys);
return a + keys <= b + keys ? a : b;
}, {});
};
minItem(stops, 'duration', 'total');