What Is Destructuring And Restructuring Design Pattern In JavaScript?

A More Declarative Approach.

Two new features introduced in JavaScript es6 were destructuring and spread. Combining both, along with default function parameters, we can create and use a design pattern called Destructuring and Restructuring, that is more declarative than the usual implementation. This pattern and its name come from Kyle Simpson.

Example

Let’s say we have a default settings object that we need values from, but we also need to add new values or override the defaults. We usually use underscore or lodash libraries for this functionality:

const defaultSettings = {
  a: "a",
  b: "b",
  c: "c",
  d: {
    e: "e",
    f: "f"
  }
};


const settings = {
  a: "A",
  b: "B",
  d: {
    m: "m"
  },
  g: "g",
  h: "h"
};

const finalSettings = _.extend(defaultSettings, settings); //underscore extend

This approach works, but it is not declarative enough, and we have to rely on the implementation detail of underscore extend to know what is happening and how we’re getting the finalSettings.

The alternative could be to use es6 features. We define a function that expect an object, assign the default values to the param object keys, destructure the ones we think might have more keys, and return the merged object with restructuring the destructured parts:

const getSettings = ({
  a = "a",
  b = "b",
  c = "c",
  d: {
    e = "e",
    f = "f",
    ...otherDs
  } = {},
  ...others
}) => {
  return {
    a, b, c, d: {
      e, f, ...otherDs
    },
    ...others
  }
}


const settings = {
  a: "A",
  b: "B",
  d: {
    m: "m"
  },
  g: "g",
  h: "h"
};

const finalSettings = getSettings(settings);

In both cases the finalSettings should have the following value:

{
  a: 'A',
  b: 'B',
  c: 'c',
  d: { e: 'e', f: 'f', m: 'm' },
  g: 'g',
  h: 'h'
}

Notice that m, g, and h are additional keys, whereas a and b have been overridden.

Where Is This Pattern Used?

This is useful with default settings or options, such as with API calls or server configurations, where you need plenty of defaults and also overridden values.




See also

When you purchase through links on techighness.com, I may earn an affiliate commission.