【问题标题】:How do I access a JSON key which was passed by argument? [duplicate]如何访问由参数传递的 JSON 密钥? [复制]
【发布时间】:2020-04-06 19:31:24
【问题描述】:

我基本上是在检查 Javascript 对象中是否存在某些指标,如果存在,我想返回它们的值。 以下是我的尝试:

public haveInIndicators(indicator: any): boolean {
    if(indicator in this.existingIndicators) {      # this condition returns true
        return this.existingIndicators.indicator;
    }
}

this.existingIndicators 是在别处定义的变量,但它返回了一个 console.log:

currency: true
__proto__: Object

通过指标的console.log 返回currency。但是,this.existingIndicators.indicator 返回undefined

如何检查传递的参数是否作为 JSON 键存在,如果确实存在则返回其值?

【问题讨论】:

  • 是这个。 existingIndicators.indicator 是一个对象,您尝试检查密钥的存在对吗?
  • indicator 是一个变量,试着读成this.existingIndicators[indicator]

标签: javascript arrays json typescript


【解决方案1】:

您可以使用Object.prototype.hasOwnProperty() 作为自己的 属性检查提供的键是否存在,并使用[] 表示法来查询动态提供的属性。

Object.prototype.hasOwnProperty() 将检查对象本身和原型链上的属性是否存在,而in 运算符将检查自己的属性以及原型链:

public haveInIndicators(indicator: string): boolean {
    if(this.existingIndicators.hasOwnProperty(indicator)) {     
        return this.existingIndicators[indicator];
    }
    return false;
}

【讨论】:

    【解决方案2】:

    要使用变量从对象中读取值,您可以使用[varName] 在这种情况下,它将是existingIndicators[indicator];

    const existingIndicators = {
    currency: true,
    };
    
    const haveInIndicators = (indicator) => {
      if(indicator in existingIndicators) {  
        return existingIndicators[indicator];
       }
    };
    
    // Or you can use an improved version of above function
    // it will fallback to "undefined" if value not present!
    const improvedHaveInIndicators = (indicator) => {
      return existingIndicators[indicator] || undefined;
    };
    
    
    const value = haveInIndicators('currency');
    
    console.log('value ', value);
    
    const improved = improvedHaveInIndicators('currency');
    
    console.log('improved ', value);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2017-12-21
      • 1970-01-01
      相关资源
      最近更新 更多