DEV Community

Cover image for How the delete operator can be your super saver
Ramya Chinnadurai
Ramya Chinnadurai

Posted on

How the delete operator can be your super saver

How the delete operator can be your super saver

In this article lets discuss how the delete operator in javascript can be your rescuer. I'm jotting down my learning and working experience, so that others may found useful.

Recently I came up with a scenario where there is an array of objects with the different fields of value, and I want to remove the unwanted fields in the object and return it as an object.

Example: Array of objects with different fields.

      rewards = [
        {
            _id: "5d6fcdf63eb318a9d6981f35",
            type: "welcome_offer",
            discount: 15,
            status: true, 
            validity: "05-09-2020"
        },
        {
           _id:"5d779b833eb318a9d6f60528",
           type: "extend_subscription",
           duration: 3,
           status: true,
           validity: "05-09-2020"
        },
        {
            _id: "5d7b700b3eb318a9d6227637",
            type: "unlock_course",
            eligiblePlans: [ "js-combo", "react-combo"],
            status: true,
            validity: "05-09-2020"
        }
    ]
Enter fullscreen mode Exit fullscreen mode

How the actual outcome should be?

    rewards: {
        "WELCOME_OFFER": {
            discount: 15,
            validity: "05-09-2020"
        },
        "EXTEND_SUBSCRIPTION": {
            duration: 3,
            validity: "05-09-2020"
        },
        "UNLOCK_COURSE": {
            eligiblePlans: [ "js-combo", "react-combo"],
            validity: "05-09-2020"
        }
    }
Enter fullscreen mode Exit fullscreen mode

So how can bring the above array to this format?

  1. Need to convert the array to object. So we can use the reduce function in javascript to convert to a single object. Okay!
  2. To capitalise the type, we can just use toUpperCase() function. Okay, that also fine.

How can we remove the unwanted fields in the object? 🤔
There comes the delete operator to rescue me.

The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
Enter fullscreen mode Exit fullscreen mode

Syntax

delete object.property
delete object['property'] 
Enter fullscreen mode Exit fullscreen mode

Okay, its time to put all the knowledge into coding.

    const eligible_rewards = rewards.reduce( ( acc, val) => {
             const type    = val.type.toUpperCase();
            const details  = {
                        [type]: {
                        ...val
                }
            }
            delete details[type].type;
            delete details[type].status;
            delete details[type]._id;
            return {...acc, ...details}
        },{})
Enter fullscreen mode Exit fullscreen mode

Checkout this snippet in JSfiddle

I'm sure there are other ways to solve the problem. Share your solution in the comment section below. I hope you find this useful. If you find useful keep supporting me. For doubts, suggestions and feedback kindly contact me at @code_rams

Discussion (4)

Collapse
savagepixie profile image
SavagePixie • Edited

Another way to do it would be mapping over it and taking only the properties we'd like to keep instead of deleting the ones we don't want, which has the advantage of not caring if in the future the object changes and has more properties.

const parseReward = ({ type, discount, duration, eligiblePlans, validity }) => [
  type.toUpperCase(),
  { discount, duration, eligiblePlans, validity }
]

const eligibleRewards = Object.fromEntries(rewards.map(parseRewards))
Collapse
blindfish3 profile image
Ben Calder

+1 to this approach. When the anticipated result is a same length array with derived data map() is the best fit; and extracting desired properties is a safer approach than mutating the source object.

I personally like reduce(), but would only use it when both filtering and deriving data.

Collapse
code_rams profile image
Ramya Chinnadurai Author

Hey SavagePixie. Thanks for sharing. Sure will try this approach in near future.

Collapse
darkwiiplayer profile image
DarkWiiPlayer

This sounds like a situation where each_with_object from Ruby would be very useful