2017-10-19 12 views
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');

答えて

1

最小値の配列にMath#minを使用して最小値を取得し、 0123を使用して作成。 argsパスの値を取得するには、Array#reduceでキーを反復処理することができます。

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 getPathValue = (src, path) => path.reduce((p, k) => typeof p === 'object' ? p[k] : p, src); 
 

 
const minItem = (array, ...args) => Math.min(...array.map((o) => getPathValue(o, args))); 
 

 
console.log(minItem(stops, 'duration', 'total'));

関連する問題