Having an object like this one:
{
"status": "OK",
"initialState": {
"id": "dc3c89d27fd2aae78287c53f952c3b6a",
"product": {
"productName": "Cars",
"description": null
},
"models": {
"Toyota Avensis": {
"id": "Toyota Avensis",
"parent": "sedan",
"required": false,
"disabled": true,
"visibility": true,
"error": false
},
"Toyota Corolla": {
"id": "Toyota Corolla",
"parent": "sedan",
"required": true,
"disabled": false,
"visibility": true,
"error": false
},
"Ford Focus": {
"id": "Ford Focus",
"parent": "sedan",
"required": false,
"disabled": true,
"visibility": true,
"error": false
},
"Ford Mondeo": {
"id": "Ford Mondeo",
"parent": "sedan",
"required": false,
"disabled": true,
"visibility": true,
"error": false
}
},
"userId": "user1",
"status": 1
}
}
I was trying to delete properties like disabled
and error
from the initialState.models
objects.
My last attempt was unsuccessful though. What I tried was something like (assuming that the object above is stored as const myObject
):
Object.entries(myObject.initialState.models).forEach(([key, value]) => {
Object.entries(value).forEach(([subKey, subValue]) => {
if (subKey === 'disabled') {
delete myObject.initialState.models[value.disabled];
}
});
});
But that way, nothing was deleted. What should be done to remove properties like disabled
and error
uncoditionally?
CodePudding user response:
Instead of iterating through the keys and values of each model, you can directly delete the disabled
and error
keys from each model:
Object.entries(myObject.initialState.models).forEach(([key, value]) => {
delete value.disabled;
delete value.error;
});
CodePudding user response:
The above answer is the best way to handle this. What mistake you did is following
Object.entries(obj.initialState.models).forEach(([key, value]) => {
Object.entries(value).forEach(([subKey, subValue]) => {
if (subKey === 'disabled') {
delete obj.initialState.models[key].disabled; // Here you did mistake
delete obj.initialState.models[key].error;
}
});});