从对象的对象中删除属性

Deleting properties from an object of objects

我正在尝试从一个对象的对象中删除一些属性我在堆栈溢出中发现了很多关于对数组执行此操作的问题,但我似乎无法找到一种干净的方法这样做是为了我的目的。

我的数据是这样的:

{ 
emr: {ID: "user-1504966781-340782", languageDesc: "English", orgId: 1504966781,…}
pcc: {ID: "user-1504966781-340782", languageDesc: "English", orgId: 1504966781,…}
}

此处的目标是从 emr 和 pcc 对象中删除比方说 languageDescorgID,同时保持对象的其余部分完好无损。我实施此更改的方式的问题是我正在尝试使用有效的 delete operator 但我必须分别从 emr 和 pcc 数据中删除 10 个项目,因此我的代码看起来不太好。谁能告诉我更好的方法来做这件事?

这是我的代码现在的样子:

const pcc = result.pcc;
const emr = result.emr;

delete pcc["MedicalPractices"];
delete pcc["CovidZone"];
delete pcc["picturePath"];
delete pcc["DoseSpotID"];
delete pcc["consentStatus"];
delete pcc["consentStatusLastUpdate"];
delete pcc["consentStatusUpdatedBy"];
delete pcc["consentStatusChangeReason"];
delete pcc["syncStatus"];
delete emr["MedicalPractices"];
delete emr["CovidZone"];
delete emr["picturePath"];
delete emr["DoseSpotID"];
delete emr["consentStatus"];
delete emr["consentStatusLastUpdate"];
delete emr["consentStatusUpdatedBy"];
delete emr["consentStatusChangeReason"];
delete emr["syncStatus"];

console.log(pcc);
this.setState({ pccData: pcc });
this.setState({ emrData: emr });

我将创建两个列表,一个是您要从中删除的对象,另一个是您要删除的属性,然后在嵌套循环中迭代它们:

const objects = ["pcc", "emr"];
const props = ["MedicalPractices", "CovidZone", "picturePath", "DoseSpotID", "consentStatus", "consentStatusLastUpdate", "consentStatusUpdatedBy", "consentStatusChangeReason", "syncStatus"];
objects.forEach(o => {
    props.forEach(p => 
        delete result[o][p];
    });
});

创建要删除的项目数组,然后循环处理每个项目。最后删除数组中提到的那些!

单独删除

let delete_items_pcc = ["MedicalPractices", "CovidZone", "picturePath" ....]
let delete_items_emr = ["MedicalPractices", "CovidZone", "picturePath" ....]
delete_items_pcc.forEach(item => delete pcc[item])
delete_items_emr.forEach(item => delete emr[item])

同时删除

let delete_items = ["MedicalPractices", "CovidZone", "picturePath" ....]
delete_items.forEach(item => {
  delete emr[item]
  delete pcc[item]
})