javascript - 使用计算的属性键访问对象值

标签 javascript object ecmascript-6

我正在编写一个小助手,它应该获取数组的最小项。

该函数采用Array 作为第一个参数和访问对象属性“rest”参数的“路径”。

例如:minItem(stops, 'duration', 'total');

console.log: //[object object][duration][total]

Expected: //Number, 即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');

最佳答案

使用 Math#min 获取最小值使用 Array#map 创建的最小值数组.要获取 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'));

关于javascript - 使用计算的属性键访问对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46828121/

相关文章:

javascript - jQuery/javascript :Overriding getElementsAtPosition(x, y) 用于获取区域元素而不是特定位置

javascript - 我怎样才能确保只提交一个表单,同时很好地使用 jQuery 验证?

java - 使用插入排序和选择排序对对象数组进行排序

javascript - 浅克隆 Map 或 Set

javascript - jQuery 验证 - 显示每个字段的错误消息

javascript - Jquery 使用验证器验证免费电子邮件

javascript - 从变量(从导入的 JS)中获取字符串作为对象中的键

c++ - iostream 不打印到第二个源类中的终端 (c++)

typescript - 是否可以在运行时传递 Typescript 装饰器对象值?

javascript - 如何解构包含函数的对象?