我有这个对象:
{
"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": "",
}
现在,我希望 specialFeatures
对象的属性键与要删除的第一个对象相同。
在此示例中,它将是:
specificFeatures": {
"coverage": "international",
"income": 0,
"observationIncome": "",
}
你能告诉我该怎么做吗?
最佳答案
要实现这一点,您可以简单地迭代对象属性,检查“原始”对象是否具有该属性,如果有,则从“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);
关于javascript - 如果对象属性存在于 Javascript/Typescript 中的另一个对象上,如何删除对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74930815/