Access Property Names with Bracket Notation

Access Property Names with Bracket Notation
0.0 0

#1

Tell us what’s happening:
Hello
I have solved this issue but solution is very ugly
here should be a more simple solution
May somebody could suggest solution with it?

Your code so far
/We’ve defined a function, checkInventory, which receives a scanned item as an argument. Return the current value of the scannedItem key in the foods object. You can assume that only valid keys will be provided as an argument to checkInventory./


let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};
// do not change code above this line

function checkInventory(scannedItem) {
  // change code below this line
return (scannedItem == 'apples')? foods.apples :  (scannedItem == 'oranges')? foods.oranges : 
(scannedItem == 'plums')? foods.plums : (scannedItem == 'bananas')? foods.bananas : (scannedItem == 'apples') ? foods.grapes : foods.strawberries;
}

// change code below this line to test different cases:
console.log(checkInventory("apples"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/access-property-names-with-bracket-notation


#2
var test =
  { foo: 1
  , bar: 2
  , baz: 3
  };

You can access object properties by name using dot notation:

test.foo // 1

But if you don’t know the name in advance, eg you have a variable:

var property = 'foo';

You can pass the variable in brackets like:

test[property]; // 1

So with that example, you have an object test and you want access a property on it represented by the variable property.

In the task, you have an object foods and you want to access a property on it represented by the variable scannedItem.