You need to enable JavaScript to run this app. ES6中如何筛选JavaScript对象内值不为null的指定属性?
优惠活动
大模型
产品
解决方案
定价
更多

ES6中如何筛选JavaScript对象内值不为null的指定属性?

问题原因

你使用剩余运算符的解构写法,仅能排除你主动解构的title、description两个属性,剩余的所有属性都会被保留,无法自动过滤掉值为null的name属性,不符合需求。

实现方案

方案1:明确提取指定属性(推荐,匹配你仅需要id、name的需求)

直接针对你需要的两个属性做过滤,不会引入原对象其他额外字段:

const values = {
    "description": "hello",
    "title": "Update",
    "id": "1",
    "name": null
};

const newValues = Object.fromEntries(
  [['id', values.id], ['name', values.name]]
    .filter(([_, value]) => value !== null)
);

console.log(newValues); // 输出:{ "id": "1" }

方案2:批量处理多个指定属性

如果后续需要提取的属性较多,可以把要提取的字段存为数组批量处理:

// 此处定义所有需要提取的属性
const requiredFields = ['id', 'name'];
const newValues = Object.fromEntries(
  requiredFields
    .map(field => [field, values[field]])
    .filter(([_, value]) => value !== null)
);

方案3:基于你原有写法调整

如果你确实需要先排除title、description,再过滤剩余所有字段的null值,可以用以下写法:

const { title, description, ...rest } = values;
const newValues = Object.fromEntries(
  Object.entries(rest).filter(([_, value]) => value !== null)
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 22:54:04