如何在JavaScript/TypeScript中移除对象与另一对象重复的属性?
问题描述
现有两个对象:
第一个基础对象:
{ "id": "33343232", "createdAt": "2022-07-26T13:44:01.080Z", "updatedAt": "2022-07-26T13:45:31.000Z", "name": "Name Here", "description": "text" }
第二个包含额外属性的对象:
"specificFeatures": { "id": "33343232", "createdAt": "2022-07-26T13:44:01.087Z", "updatedAt": "2022-07-26T13:45:31.000Z", "name": "Name Here", "description": "text", "coverage": "international", "income": 0, "observationIncome": "" }
需要删除specificFeatures对象中与第一个对象属性键相同的属性,最终得到:
"specificFeatures": { "coverage": "international", "income": 0, "observationIncome": "" }
实现方法
以下是几种JavaScript的实现方式:
方法1:直接删除原对象的重复属性
先拿到第一个对象的所有属性键,遍历这些键从specificFeatures里删掉对应属性:
const baseObj = { "id": "33343232", "createdAt": "2022-07-26T13:44:01.080Z", "updatedAt": "2022-07-26T13:45:31.000Z", "name": "Name Here", "description": "text" }; const targetObj = { "id": "33343232", "createdAt": "2022-07-26T13:44:01.087Z", "updatedAt": "2022-07-26T13:45:31.000Z", "name": "Name Here", "description": "text", "coverage": "international", "income": 0, "observationIncome": "" }; // 获取基础对象的属性键集合 const baseKeys = Object.keys(baseObj); // 遍历删除重复属性 baseKeys.forEach(key => { delete targetObj[key]; }); console.log(targetObj); // 输出结果即为只保留差异属性的对象
方法2:创建新对象(不修改原对象)
如果不想改动原specificFeatures对象,可生成一个新对象只保留不重复的属性:
const baseObj = { "id": "33343232", "createdAt": "2022-07-26T13:44:01.080Z", "updatedAt": "2022-07-26T13:45:31.000Z", "name": "Name Here", "description": "text" }; const targetObj = { "id": "33343232", "createdAt": "2022-07-26T13:44:01.087Z", "updatedAt": "2022-07-26T13:45:31.000Z", "name": "Name Here", "description": "text", "coverage": "international", "income": 0, "observationIncome": "" }; const baseKeys = new Set(Object.keys(baseObj)); // 筛选出不在基础对象中的属性,构建新对象 const filteredObj = Object.fromEntries( Object.entries(targetObj).filter(([key]) => !baseKeys.has(key)) ); console.log(filteredObj); // 输出目标结果
方法3:解构赋值快速过滤
若基础对象的属性固定且数量不多,用解构赋值+剩余参数能快速提取需要保留的属性:
const baseObj = { "id": "33343232", "createdAt": "2022-07-26T13:44:01.080Z", "updatedAt": "2022-07-26T13:45:31.000Z", "name": "Name Here", "description": "text" }; const targetObj = { "id": "33343232", "createdAt": "2022-07-26T13:44:01.087Z", "updatedAt": "2022-07-26T13:45:31.000Z", "name": "Name Here", "description": "text", "coverage": "international", "income": 0, "observationIncome": "" }; // 解构出基础对象的属性,剩余的就是要保留的 const { id, createdAt, updatedAt, name, description, ...filteredObj } = targetObj; console.log(filteredObj); // 得到目标结果
内容的提问来源于stack exchange,提问作者Renan Bessa
相关产品推荐
相关产品推荐

