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

如何根据属性列表从JavaScript对象中提取指定属性?

从对象中提取指定属性的实现方法

场景回顾

现有源对象:

const someObject = { number: '1', month: 'march', year: '2023' }

需要提取的属性支持两种格式:

  • 数组形式:const someArray = ['month', 'year']
  • 字符串形式:'month, year'
    最终要得到目标对象:
const finalObject = { month: 'march', year: '2023' }

1. 处理数组形式的属性列表

如果属性列表是数组,用Object.fromEntries()结合map()是最简洁的实现方式,直接映射键值对后构建新对象:

const someArray = ['month', 'year'];
const finalObject = Object.fromEntries(
  someArray.map(key => [key, someObject[key]])
);

要是需要兼容ES6之前的环境,手动遍历的方式更稳妥:

const someArray = ['month', 'year'];
const finalObject = {};
for (const key of someArray) {
  // 可选:校验属性是否存在,避免添加undefined值
  if (someObject.hasOwnProperty(key)) {
    finalObject[key] = someObject[key];
  }
}

2. 处理字符串形式的属性列表

先把逗号分隔的字符串转换成标准数组,再复用数组形式的提取逻辑即可:

const propString = 'month, year';
// 分割字符串并去除每个属性的首尾空格
const propArray = propString.split(',').map(item => item.trim());
// 生成目标对象
const finalObject = Object.fromEntries(
  propArray.map(key => [key, someObject[key]])
);

3. 通用函数(兼容两种输入格式)

封装一个函数自动判断输入类型,统一处理两种场景:

function extractProperties(sourceObj, props) {
  let propArray;
  // 识别输入类型并转为数组
  if (Array.isArray(props)) {
    propArray = props;
  } else if (typeof props === 'string') {
    propArray = props.split(',').map(item => item.trim());
  } else {
    throw new Error('属性列表必须是数组或逗号分隔的字符串');
  }
  
  // 过滤不存在的属性并返回新对象
  return Object.fromEntries(
    propArray
      .filter(key => sourceObj.hasOwnProperty(key))
      .map(key => [key, sourceObj[key]])
  );
}

// 使用示例
const someObject = { number: '1', month: 'march', year: '2023' };
// 传入数组参数
console.log(extractProperties(someObject, ['month', 'year']));
// 传入字符串参数
console.log(extractProperties(someObject, 'month, year'));

关键注意点

  • 所有实现都会返回全新对象,不会修改原有的someObject;
  • 加入hasOwnProperty校验可以避免提取源对象中不存在的属性,防止新对象出现undefined值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:43:21