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

JavaScript对象筛选:提取值为1的属性

提取JavaScript对象中值为1的属性

给定对象:

let arr = {tp:1, op:1, lp:0, co:0}

要提取其中值为1的属性到新对象,这里提供两种实用方法:

方法一:使用Object.entries结合reduce

let arr = {tp:1, op:1, lp:0, co:0};
const filteredObj = Object.entries(arr).reduce((newObj, [key, val]) => {
  if (val === 1) {
    newObj[key] = val;
  }
  return newObj;
}, {});
console.log(filteredObj); // 输出 { tp: 1, op: 1 }

方法二:使用for...in循环

let arr = {tp:1, op:1, lp:0, co:0};
const filteredObj = {};
for (const key in arr) {
  if (arr[key] === 1) {
    filteredObj[key] = arr[key];
  }
}
console.log(filteredObj); // 输出 { tp: 1, op: 1 }

两种方法核心逻辑一致:遍历原对象的键值对,筛选出值等于1的属性,将其添加到新对象中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:35:20