首页 > 解决方案 > 我可以将解构的数组赋值分配给变量并对其进行解构吗?

问题描述

我想知道是否有办法解构一个数组,为其分配一个变量,然后将值传递给同一行上的另一个解构变量。请在下面查看我打算做什么:

const { prop } = [a] = chips.filter(x => x.id == 1);

通常,我会在两行代码中执行此操作,如下所示:

const [a] = chips.filter(x => x.id == 1);
const { prop } = a;

我可以在一行上做到这一点吗?

标签: javascript

解决方案


当然,只需将{ 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);


推荐阅读