javascript - 我可以将解构的数组赋值分配给变量并对其进行解构吗?
问题描述
我想知道是否有办法解构一个数组,为其分配一个变量,然后将值传递给同一行上的另一个解构变量。请在下面查看我打算做什么:
const { prop } = [a] = chips.filter(x => x.id == 1);
通常,我会在两行代码中执行此操作,如下所示:
const [a] = chips.filter(x => x.id == 1);
const { prop } = a;
我可以在一行上做到这一点吗?
解决方案
当然,只需将{ prop }
内部放在a
当前所在的位置:
const [{ prop }] = chips.filter(x => x.id == 1);
const chips = [
{ id: 1, prop: 'foo'},
{ id: 1, prop: 'bar'},
{ id: 1, prop: 'baz'}
];
const [{ prop }] = chips.filter(x => x.id === 1);
console.log(prop);
(请注意,如果可能,您也可以考虑使用严格的相等比较===
)
但是,如果您只想使用数组中的第一个.find
匹配元素,则使用而不是更合适.filter
,因为.find
返回找到的元素,而filter
返回一个数组(您并没有真正使用):
const chips = [
{ id: 1, prop: 'foo'},
{ id: 1, prop: 'bar'},
{ id: 1, prop: 'baz'}
];
const { prop } = chips.find(x => x.id === 1);
console.log(prop);
推荐阅读
- android - 设备所有者应用在辅助用户中没有权限
- amazon-s3 - AWS Glue:使用作业书签进行增量加载时无法推断架构
- android - Migrate method RxJava1 to RxJava2
- r - Firth's Logistic Regression
- sql - 按选择部分中的 CAST 字段分组?
- r - R 官员 更新形状的文本
- java - 如何在 Junit5 和 JDK11 中使用 Powermock?
- flutter - How to access config file in flutter using bloc architecture
- r - 尝试在 RStudio 中安装包(重包和中位数)时出现问题
- deep-learning - How do I calculate cross-entropy from probabilities in PyTorch?