如何在JavaScript中比较键值并从主对象移除指定对象
在JavaScript中移除包含指定属性的对象子项
假设你需要从一个以日期为键的对象中,移除所有包含selected: true属性的子对象,下面是几种实用的实现方式:
方法一:直接修改原对象(使用delete操作符)
如果不需要保留原对象,直接遍历对象的键,判断子对象的属性后删除对应项即可:
const mainObject = { "2022-10-29": { "disabled": true, "disableTouchEvent": true }, "2022-10-26": { "selected": true, "selectedColor": "#3634A3", "selectedTextColor": "#FFFFFF" }, "2022-10-30": { "disabled": true, "disableTouchEvent": true }, "2022-11-05": { "disabled": true, "disableTouchEvent": true } }; // 遍历所有键,删除符合条件的子对象 for (const key in mainObject) { // 检查子对象是否存在selected属性且值为true if (mainObject[key].selected === true) { delete mainObject[key]; } } // 此时mainObject即为期望的finalObject console.log(mainObject);
这种方式操作简单直接,但会改变原对象的结构,如果需要保留原对象,推荐用下面的方法。
方法二:生成新对象(不修改原对象)
通过Object.entries和Object.fromEntries组合,过滤掉不符合条件的子项,生成新对象:
const mainObject = { "2022-10-29": { "disabled": true, "disableTouchEvent": true }, "2022-10-26": { "selected": true, "selectedColor": "#3634A3", "selectedTextColor": "#FFFFFF" }, "2022-10-30": { "disabled": true, "disableTouchEvent": true }, "2022-11-05": { "disabled": true, "disableTouchEvent": true } }; // 过滤出selected不为true的子项,构建新对象 const finalObject = Object.fromEntries( Object.entries(mainObject).filter(([key, value]) => value.selected !== true) ); console.log(finalObject);
这种方式不会修改原对象,符合函数式编程的无副作用原则,适合需要保留原数据的场景。
方法三:使用reduce构建新对象
另一种生成新对象的方式是用Array.reduce,逻辑和方法二类似:
const finalObject = Object.keys(mainObject).reduce((result, key) => { const item = mainObject[key]; // 只保留selected不为true的子对象 if (item.selected !== true) { result[key] = item; } return result; }, {}); console.log(finalObject);
注意事项
如果部分子对象可能不存在selected属性,建议在判断时增加存在性检查,避免出现undefined判断的问题:
// 安全判断写法 if (mainObject[key] && mainObject[key].selected === true) { // 执行删除或过滤逻辑 }
内容的提问来源于stack exchange,提问作者harika
相关产品推荐
相关产品推荐

