【问题标题】:Typescript name of key in Object对象中键的打字稿名称
【发布时间】:2019-01-16 05:38:45
【问题描述】:

假设我们有这样的对象:

foo = {
   "currency": "dollar"
}

是否可以检查对象的值是否存在并且等于美元? 例如:

const bar = currency;

那么我们如何将 bar 的值传递给 foo 路径呢?或者使用任何应该用作 $bar 的语法?我不想将 $bar 作为路径名传递,而是将 bar 的值作为路径传递。

foo.$bar? true: false
in result  foo.currency === true or false

甚至可以有另一个对象,例如:

anotherobject.anotherpath.$(getKey(foo))

要像 anotherobject.anotherpath.currency 这样的对象?
希望它足够清楚,可以理解

【问题讨论】:

  • 您是否正在寻找foo[bar]?喜欢foo[bar] == "dollar"
  • @Aioros,伙计,我不想检查值,但如果存在特定路径。这样我想确定路径 foo.$bar 是否存在,其中 $bar = currency.
  • 你可以if (bar in foo && foo[bar] === 'dollar') where bar = 'currency' developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript typescript


【解决方案1】:

对象的行为有点像数组,您可以使用括号表示法访问存储在某个索引中的值 - 但在这种情况下,使用键或字段代替数字索引。

所以你可以:

const foo = { "currency": "dollar" };
const bar = "currency"

if (foo[bar] == "dollar") { /* do something */ }

如果要检查 foo 对象中是否存在 'bar' 属性,也可以这样做:

const foo = { "currency": "dollar" };
const bar = "currency"

// will check if foo.bar exists
if (foo.hasOwnProperty(bar)) {/* do something */}

【讨论】:

  • 正如我所提到的,我不想检查“货币”的价值是否为“美元”,但我想检查 foo.$bar 是否存在,其中 $bar = 货币 :)
  • hasOwnProperty 函数会检查 foo 对象是否有 'currency' 字段,这是你需要的吗?
【解决方案2】:
var foo = {
   "currency": "dollar"
};
var bar = "currency";

检查密钥是否存在:

if (foo[bar])

或者:

if (foo.hasOwnProperty(bar))

检查属性是否具有正确的值

if (foo[bar] == "dollar")

【讨论】:

    【解决方案3】:

    你可以使用Object.values():

    示例如下:

    var foo = {
       "currency": "dollar"
    };
    var bar = "currency";
    
    
    console.log(Object.values(foo).indexOf(bar) >= 0); //false
    console.log(Object.keys(foo).indexOf(bar) >= 0); //true
    

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 1970-01-01
      • 2021-06-28
      • 2017-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      • 2014-08-07
      相关资源
      最近更新 更多