简体   繁体   中英

Deleting properties from an object of objects

I am trying to remove a number of properties from an object of objects I've found a lot of questions on stack overflow about doing this for array but I can't seem to figure out a clean way of going about doing this for my purposes.

My data looks like this:

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

The goal here is to remove let's say languageDesc , and orgID from the emr and pcc objects while keeping the rest of the object intact. The issue with the way I'm implementing this change is I am trying to use the delete operator which works but I have to delete 10 items from the emr and pcc data separately so my code does not look good. Can anyone show me a better way to go about doing this?

this is what my codes looking like right now:

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 });

I'd create two lists, one of the objects you want to delete from and one of the properties you want to delete and iterate over them in a nested loop:

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];
    });
});

Creating an array of items you want to delete and then just looping for each item. Finally deleting those mentioned in arrays !

Deleting separately

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])

Deleting simultaneously

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM