简体   繁体   English

如何从常量开始解构 object?

[英]How destructure an object starting from a constant?

I have a utils/constant.js file with:我有一个utils/constant.js文件:

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

I need to access to totalElements via the constant.我需要通过常量访问totalElements

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

Edit: As @pilchard mentioned, using Object.prototype.hasOwnProperty is a better way of doing this in case the value is falsy:编辑:正如@pilchard提到的,使用Object.prototype.hasOwnProperty是一种更好的方法,以防值为假:

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.原始答案:虽然@jsN00b提供的答案有效并且更接近 OP 的@sineverba代码,但这里存在一个问题,因为in运算符会检查指定的object及其原型链中的指定属性。

This means that, for example, if data s prototype is Object.prototype , something like 'toString' in data would work as well.这意味着,例如,如果data的原型是Object.prototype ,那么数据中的'toString' in data类的东西也可以工作。

For that reason, you could use something like the following to only check for the 'totalElements' key in the object itself, and avoid destructuring:出于这个原因,您可以使用类似以下的方法来仅检查 object 本身中的'totalElements'键,并避免解构:

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

The desired objective is:期望的目标是:

  • use the constant TOTAL_ELEMENTS (& not directly the prop-name)使用常量TOTAL_ELEMENTS (而不是直接使用道具名称)
  • check if data has the corresponding prop检查data是否有对应的prop
  • if found, then return the value of the prop如果找到,则返回 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.注意上面没有de-structure数据。 It access the corresponding prop directly without the need to destructure.它直接访问相应的 prop 而无需解构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM