1

我正在养成根据上下文将我的一些转换for loops为 use的习惯array.find()。这样做时,我想知道是否有一种方法可以在之后链接另一个运算符,.find()以限制我从对象中抓取的数量。

例如,请参阅以下内容:

currentStage = customerDoc.history.find(h => h.completed === false);
currentStageName = currentStage.name;

由于我真正想要的只是“currentStage.name”的值,有没有办法通过在 my 之后链接来获得这个find(),以指定我只想要这个属性?如果没有,是否有另一种方法可以在一行中做到这一点?

4

4 回答 4

4

是的,你可以喜欢这个,注意使用|| {}以避免异常,以防 find 返回 undefined

currentStage = (customerDoc.history.find(h => h.completed === false) || {}).name

但是 IMO 你应该像现在一样保留它,它可读且易于维护

currentStage = customerDoc.history.find(h => h.completed === false);
currentStageName = currentStage && currentStage.name;
于 2019-07-25T19:07:31.897 回答
4

您可以使用可选链(目前是 TC39 的第 3 阶段提案,尚未在浏览器中实现),但现在可以使用babel 的插件并使用它:

const currentStageName = customerDoc.history.find(h => !h.completed)?.name;
于 2019-07-25T19:11:26.943 回答
3

使用短路评估来获得一个默认对象,以防万一找不到,并解构以获得您想要的属性。如果什么也没找到,结果将是undefined

const { name: currentStageName } = customerDoc.history.find(h => h.completed === false) || {};
于 2019-07-25T19:08:08.770 回答
1

您还可以将 .map 链接到查找结果上,以便通过将其包装在数组中来限制和/或重塑返回的内容(如果未找到结果则使用过滤器),例如

currentStage = [customerDoc.history.find(h => h.completed === false)].filter(h => h != undefined).map(h => ({'name':h.name}))[0]
于 2021-02-13T02:18:35.547 回答