Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

243
Visualizações
How destructure an object starting from a constant?

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;
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Edit: As @pilchard mentioned, using Object.prototype.hasOwnProperty is a better way of doing this in case the value is falsy:

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

Original answer: While the answer @jsN00b provided works and is closer to OP's @sineverba code, there's an issue here since the in operator checks for the specified property in both the specified object AND its prototype chain.

This means that, for example, if datas prototype is Object.prototype, something like 'toString' in data would work as well.

For that reason, you could use something like the following to only check for the 'totalElements' key in the object itself, and avoid destructuring:

if (data[TOTAL_ELEMENTS]) {
  return data[TOTAL_ELEMENTS]
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda