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
相关产品推荐
相关产品推荐

