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

JavaScript中移除对象数组空属性,保留指定字段(如note)

如何移除对象数组中除指定字段外的所有null值属性

给定如下对象数组:

const arr = [{
    id: 1,
    name: 'John',
    lastName: 'Smith',
    note: null
  },
  {
    id: 2,
    name: 'Jill',
    lastName: null,
    note: 'note 2'
  },
  {
    id: 3,
    name: null,
    lastName: 'Smith',
    note: null
  }
];

需求:移除所有对象中的null值属性,但保留note字段(即使它为null),预期输出:

[{
    id: 1,
    name: 'John',
    lastName: 'Smith',
    note: null
  },
  {
    id: 2,
    name: 'Jill',
    note: 'note 2'
  },
  {
    id: 3,
    lastName: 'Smith',
    note: null
  }
];

原有的逐个字段判断的方法在字段较多时过于繁琐,以下是更优解决方案:


方案一:原生JavaScript实现

通过Object.entries遍历对象键值对,结合reduce构建处理后的新对象,再用map处理整个数组,无需依赖第三方库:

// 定义处理单个对象的函数
const cleanObject = (obj) => {
  return Object.entries(obj).reduce((result, [key, value]) => {
    // 规则:如果是note字段则直接保留;否则仅保留非null的值
    if (key === 'note' || value !== null) {
      result[key] = value;
    }
    return result;
  }, {});
};

// 处理整个数组
const processedArray = arr.map(cleanObject);

注意:该方法返回新数组与新对象,不会修改原数组,避免副作用。


方案二:Ramda库实现

利用Ramda的函数式工具链,可以更简洁地实现需求:

// 定义单个对象的清理逻辑:移除"值为null且不是note字段"的键值对
const cleanObject = R.reject((value, key) => value === null && key !== 'note');

// 批量处理数组
const processedArray = R.map(cleanObject, arr);

也可以写成更紧凑的链式调用:

const processedArray = R.map(
  R.reject((val, key) => val === null && key !== 'note'),
  arr
);

Ramda的实现更贴合函数式编程风格,适合已有Ramda依赖的项目。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:55:17