0

I'm basically checking if certain indicators exist in a Javascript Object and if they exist, I want to return their value. Here's how I'm trying to do it:

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

this.existingIndicators is a variable defined somewhere else, but a console.log on it returns:

currency: true
__proto__: Object

A console.log on the passed indicator returns currency. However, this.existingIndicators.indicator returns undefined.

How can I check if the passed argument does exist as a JSON key and return its value if it indeed exists?

Caio Costa
  • 74
  • 1
  • 9

2 Answers2

1

You can use the Object.prototype.hasOwnProperty() to check for the presence of the supplied key as an own property and the [] notation to query for dynamically supplied properties.

The Object.prototype.hasOwnProperty() will check for the presence of the property on the object itself and not on the prototype chain, whereas the in operator will check in the own properties as well as on the prototype chain:

public haveInIndicators(indicator: string): boolean {
    if(this.existingIndicators.hasOwnProperty(indicator)) {     
        return this.existingIndicators[indicator];
    }
    return false;
}
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
1

To read a value from object using a variable, you can use [varName] in this case, it will be 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);
Tareq
  • 5,283
  • 2
  • 15
  • 18