json - 如何在 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": "",
}
你能告诉我我该怎么做吗?
答案#1
为了实现这一点,你可以简单地遍历对象属性,检查“original”对象是否具有该属性,如果有,则从“specificFeatures”对象中删除它:
const original = {
"id": "33343232",
"createdAt": "2022-07-26T13:44:01.080Z",
"updatedAt": "2022-07-26T13:45:31.000Z",
"name": "Name Here",
"description": "text",
}
const 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": "",
}
// Iterate over object keys
Object.keys(specificFeatures).forEach(prop => {
// Check if the "original" object has the property defined
if (original.hasOwnProperty(prop)) {
// Delete the property from the "specificFeatures" object
delete specificFeatures[prop];
}
});
console.log(specificFeatures);注意,这种方式会修改原始对象,如果你需要保持原始对象不变,则应创建一个新的唯一副本。可能的解决方案之一是结合使用 Object.entries() 和 Array.reduce() 方法:
const original = {
"id": "33343232",
"createdAt": "2022-07-26T13:44:01.080Z",
"updatedAt": "2022-07-26T13:45:31.000Z",
"name": "Name Here",
"description": "text",
}
const 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": "",
}
const result = Object.entries(specificFeatures).reduce((acc, [key, val]) => {
if (!original.hasOwnProperty(key))
acc[key] = val;
return acc;
}, {});
console.log(result);
console.log('Is a different object:', result !== specificFeatures);答案#2
这可以通过一个简单的一行代码实现:
var 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": "",
}
var myObj = {
"id": "33343232",
"createdAt": "2022-07-26T13:44:01.080Z",
"updatedAt": "2022-07-26T13:45:31.000Z",
"name": "Name Here",
"description": "text",
}
const newObj = Object.fromEntries(Object.entries(specificFeatures).filter(([key]) => !(myObj.hasOwnProperty(key))));
console.log(newObj);上述操作将对象转换为条目数组,然后在转换回对象之前根据 myObj 筛选键。
