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

如何在JavaScript中从对象数组提取指定键值对?

从JavaScript对象数组中提取指定字段的实现方法

现有如下JavaScript数据:

records = [{id: 231, first_name: "Jack", last_name: "Aston", email: "jack55@xyz.com"}, {id: 232, first_name: "Roy", last_name: "Dillon", email: "roy@xy.com"}, {id: 233, first_name: "Jacy", last_name: "Wilson", email: "jacy@x.com"}]

fields = ['id', 'email', 'last_name']

需要从records数组中仅提取fields指定的字段,得到如下格式的新数组:

new_records = [{id: 231, email: "jack55@xyz.com", last_name: "Aston"}, {id: 232, email: "roy@xy.com", last_name: "Dillon"}, {id: 233, email: "jacy@x.com", last_name: "Wilson"}]

下面是几种可行的实现方式:

方法一:map + reduce 组合

遍历数组每个对象,通过reduce筛选指定字段并构建新对象,适合字段数量不固定的场景:

const new_records = records.map(record => {
  return fields.reduce((acc, field) => {
    acc[field] = record[field];
    return acc;
  }, {});
});

方法二:map + 对象解构

如果明确知道要提取的字段,用解构赋值写法更简洁直观:

const new_records = records.map(({ id, email, last_name }) => ({ id, email, last_name }));

方法三:封装通用工具函数

如果需要多次复用提取逻辑,可以封装成工具函数,传入数据源和目标字段即可:

function extractFields(data, fields) {
  return data.map(item => {
    const result = {};
    fields.forEach(field => {
      if (item.hasOwnProperty(field)) {
        result[field] = item[field];
      }
    });
    return result;
  });
}

// 调用示例
const new_records = extractFields(records, fields);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:05:27