loading...
Cover image for How the delete operator can be your super saver

How the delete operator can be your super saver

code_rams profile image rams.dev ・2 min read

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"
        }
    ]

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"
        }
    }

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.

Syntax

delete object.property
delete object['property'] 

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}
        },{})

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

Posted on by:

code_rams profile

rams.dev

@code_rams

Passionate programmer and curious learner. Sharing my learning experience in the form of words and letters.

Discussion

pic
Editor guide
 

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

+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.

 

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

 

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