You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过数组解构直接提取每个元素的属性生成新数组?

能否通过数组解构直接提取属性数组?

现有如下数组:

const a = [ {p:1}, {p:2}, {p:3} ];

能否通过解构该数组得到 p = [1, 2, 3]?

尝试以下写法无法实现:

const [ ...{ p } ] = a;   // 无报错,等同于 const p = a.p;
// p = undefined;

补充说明

我已经了解Array.prototype.map的用法,仅想确认是否可在解构过程中直接完成属性映射——结论是不能,需先解构数组再单独调用map。

示例如下:

const data = {
   id: 123,
   name: 'John',
   attributes: [{ id:300, label:'attrA' }, { id:301, label:'attrB' }]
};

function format(data) {
  const { id, name, attributes } = data;
  const attr = attributes.map(({ label }) => label);
  return { id, name, attr };
}

console.log( format(data) );
// { id:123, name:'John', attr:['attrA', 'attrB'] }

我想确认:是否存在无需使用map(也不使用lodash库),直接在解构阶段就将所有label属性提取为字符串数组的方法?


内容的提问来源于stack exchange,提问作者Yanick Rochon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 09:21:01