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

如何用Object.entries与Reduce筛选exist为true的对象键值对

解决方法:过滤出exist === true的对象键

你这里的问题出在判断条件的写法上,this.key.exist完全不符合当前的变量逻辑,咱们来一步步修正:

错误原因分析

在reduce的回调函数里,[key, val]是解构出来的当前键名和对应的值(也就是每个子对象,比如{ exist: true }),你不需要用this,直接访问val.exist就能拿到对应子对象的exist属性值。

修正后的Reduce写法

const someObj = { super: { exist: true }, photo: { exist: true }, request: { exist: false } }

const newObj = Object.entries(someObj).reduce((acc, [key, val]) => { 
  // 直接判断子对象的exist属性是否为true
  if (val.exist === true) { 
    return { ...acc, [key]: val } 
  }
  // 不符合条件时要返回原累加器,否则会返回undefined导致错误
  return acc;
}, {});

console.log(newObj); 
// 输出: { super: { exist: true }, photo: { exist: true } }

注意:一定要记得在条件不满足时返回原累加器acc,否则当遇到不符合条件的项时,回调函数会默认返回undefined,导致后续的累加逻辑出错。

更简洁的写法:用Object.fromEntries + filter

如果觉得reduce写起来有点繁琐,还可以结合Object.fromEntries和filter来实现,代码更直观:

const someObj = { super: { exist: true }, photo: { exist: true }, request: { exist: false } }

const newObj = Object.fromEntries(
  Object.entries(someObj).filter(([_, val]) => val.exist === true)
);

console.log(newObj);
// 输出同样是: { super: { exist: true }, photo: { exist: true } }

这里用_来表示不需要用到的键名变量,是一种常见的代码习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:27:11