Can I call an object's key-value pair by it's name?

I’m working on this for fun and I’ve encountered an issue:

const stock = {
  _goblinToy: 3000,
  _ghostToy: 2500,
  _treeSpiritToy: 2750,
  get goblinToy() {
    return this._goblinToy;
  }
}
const orderedItems = [];
const placeOrder = (item) => {
  orderedItems.push(item);
  if(stock.item) {
    console.log(`The item you are searching for exists`);
  } else {
    console.log(`Sorry, that order is invalid.`);
  }
}
placeOrder(stock._goblinToy);
console.log(orderedItems);

The last line logs 3000, how do I make it print goblinToy?

You could add this as a method on the object:

getKeyByIndex(indexOfKey) {
  return Object.keys(this)[indexOfKey]
}

// Then
console.log(stock.getKeyByIndex(1))
// logs _goblinToy

To explain, Object.keys(givenObject) returns an array with the key names of all the key-value pairs of a given object. Then, we’re returning the key name at the index of the array - essentially, it’s position within the object. Similarly, Object.entries(givenObject) returns the key-value pairs entirely, and Object.values(givenObject) returns an array of just the values.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.