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

如何从对象数组中提取多键对应值并重组为指定结构?

提取对象数组中多个键值的两种实现方案

针对你的对象数组,以下是两种期望输出的具体实现:

第一种输出:按键分组的对象数组

要得到[{ foo: [1, 3, 5] }, { bar: [2, 4, 6] }]结构,可通过遍历目标键、收集对应值来实现:

const objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];
const targetKeys = ['foo', 'bar'];

const newObj = targetKeys.map(key => ({
  [key]: objArray.map(item => item[key])
}));

执行后newObj即为你需要的第一种格式。

第二种输出:值数组的嵌套数组

要得到[[1, 3, 5], [2, 4, 6]]结构,可直接提取每个键的所有值组成数组:

const objArray = [ { foo: 1, bar: 2}, { foo: 3, bar: 4}, { foo: 5, bar: 6} ];

// 固定键的写法
const newObj = [
  objArray.map(item => item.foo),
  objArray.map(item => item.bar)
];

// 通用写法(适用于键数量不确定的场景)
const targetKeys = ['foo', 'bar'];
const newObj = targetKeys.map(key => objArray.map(item => item[key]));

两种写法都能得到你需要的第二种格式。

你的原有代码问题说明

你之前写的const newObj = objArray.map(({ foo, bar }) => ( foo, bar )),其中(foo, bar)是逗号运算符,只会返回最后一个表达式的值bar,所以最终结果是[2, 4, 6],无法满足提取多个键值的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 00:55:17