My task is to write a function that takes an object like the one below and deletes the "shelvesInCupboards" and "shelvesNotInCupboards" properties if they are present and adds a new property with their sum "totalShelves". I am not sure how to add my respective delete statements to get rid of the two mentioned properties without also altering my new "totalShelves" value.
Example object:
{
shelvesInCupboards: 3,
shelvesNotInCupboards: 2,
};
function sortTheKitchen(kitchen) {
kitchen["totalShelves"] = 0;
if (kitchen["shelvesInCupboards"] && kitchen["shelvesNotInCupboards"]) {
totalShelves = kitchen["shelvesInCupboards"] + kitchen["shelvesNotInCupboards"]
}
if (kitchen["shelvesInCupboards"] && !kitchen["shelvesNotInCupboards"]) {
totalShelves = kitchen["shelvesInCupboards"]
}
if (!kitchen["shelvesInCupboards"] && kitchen["shelvesNotInCupboards"]) {
totalShelves = kitchen["shelvesNotInCupboards"]
}
return kitchen;
}
2
Answers
It quite simple, just delete the property after you get the value
totalShelves
. And you should use nullish operator combine with optional chaining to simplify your function.You can use
Array::reduce()
to sum any number of object properties and delete them simultaneously: