所以我有一个项目列表
const items = this.props.complex_object?.items;
我想根据键对这些项目进行排序。我自然想执行以下操作
const sortedItems = this.props.complex_object?.items.sort(
(a, b) => a?.confidence > b?.confidence
);
但是我收到以下流程错误。
Flow does not yet support method or property calls in optional chains.
这有点道理,因为 items
属于流类型?Array<ItemType>
。鉴于 Items
存在的条件性质,我尝试检查 null 和未定义
var items = this.props.complex_object?.items;
if (items === null || items === undefined)
items = [];
const sortedItems = items.sort((a, b) => a. confidence > b.confidence);
return (<Table items=sortedItems>);
但这并不能缓解问题。底线是,如何对可选对象数组进行排序?
非常感谢
最佳答案
如果您知道 props.complex_object
将始终存在,您可以这样做
var items = this.props.complex_object.items || [];
如果 items
在您的 complex_object
上不存在(未定义),或者存在但值为 undefined
或 null
,那么它将默认为空数组。
关于javascript - 如何在 Javascript(和 Flow)中使用条件访问根据键对对象列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56856668/