Amiga500
Amiga500

Reputation: 6131

Destructuring objects in Javascript

In my code base I have an object:

let myObject = {
  "version": 1,
  "traceId": "123456789",
  "session": {},
  "trigger": {
    "service": "some_service_is_here",
    "action": "update",
    "resource": "transaction"
  },
  "changesets": [
    {
      "update": {
        "retryCount": 1
      },
      "conditions": {
        "equal": {
          "subscriptionId": "aaaaaaaaaaaa",
          "transactionId": "bbbbbbbbbbbb"
        }
      }
    },
    {
      "update": {
        "retryCount": 2
      },
      "conditions": {
        "equal": {
          "subscriptionId": "ccccccccccccc",
          "transactionId": "dddddddddddddd"
        }
      }
    }
  ]
}

I need to extract some properties from that object. So far it is done using Lodash. There are more extractions going on, but they are fairly identical. Several examples of using it with Lodash:

const trigger = _.get(myObject, 'trigger', null);
const retryCount = _.get(myObject, 'changesets[0].update.retryCount', null);

It works and behaves as expected. I would like to improve this code, by eliminating Lodash and start using Destructuring.

So far I have this:

const trigger = _.get(myObject, 'trigger', null);

becomes

const {trigger} = myObject;

And also:

const retryCount = _.get(myObject, 'changesets[0].update.retryCount', null);

becomes

const {changesets: [{update:{retryCount:retryCount = null}}]} = myObject;

It also works, test are passing:

Now I have several questions:

  1. Is this the correct practice to extract those values?

  2. Is it worth it, in terms of speed and code readability?

  3. The second destructuring example. I will receive an changeset array, that has many objects (unknown number), but I am always interested in the first one. The lodash example illustrates that. When I destructure, I do not specify that I need a first one (zero based) it comes in by default. Do I need somehow to specify I need the zeroth one, or it is default behaviour?

Upvotes: 1

Views: 102

Answers (1)

skyboyer
skyboyer

Reputation: 23705

  1. Yes, but currently your variants are not equal. You need to specify null to be default value in variant with destructuring .
  2. Code is not faster. As for readability - it depends.
  3. You currently specify index explicitly by items' position in the list. So for example

    const {changesets: [,,{update}]} = myObject;
    

    would explicitly extract 3rd element. You don't need to do anything extra.

PS retryCount:retryCount better don't specify the same name twice. it looks confusing. Reader(like me) will re-read for several times trying to figure out the difference.

Upvotes: 1

Related Questions