Home > Software design >  How destructure an object starting from a constant?
How destructure an object starting from a constant?

Time:03-12

I have a utils/constant.js file with:

// Key of total elements in remote collection
export const TOTAL_ELEMENTS = "totalElements";

I need to access to totalElements via the constant.

import { TOTAL_ELEMENTS } from "./constants.js";
[...]
let data = {
    content: "foo",
    totalElements: 54
};

if(TOTAL_ELEMENTS in data) {
    // pseudocode, of course it doesn't work.
    // of course in my case need to return 54
    const { TOTAL_ELEMENTS } = data;
    return TOTAL_ELEMENTS;
}

CodePudding user response:

You could use something like

if (data[TOTAL_ELEMENTS]) {
  return data[TOTAL_ELEMENTS]
}

CodePudding user response:

The desired objective is:

  • use the constant TOTAL_ELEMENTS (& not directly the prop-name)
  • check if data has the corresponding prop
  • if found, then return the value of the prop

The below code-sample may be one solution to achieve the desired objective:

if (TOTAL_ELEMENTS in data) return data[TOTAL_ELEMENTS];

NOTE The above does not de-structure the data. It access the corresponding prop directly without the need to destructure.

  • Related