Using bracket notation to access property values of an object

Using bracket notation to access property values of an object
0

#1

short solution but first understand this
here we have parameter = scanItems and argument= foods{propertiesNames}
so we will assign scannedItems=foods[i] in a new function with parameter i because we dont have that in main function.
soultion here:

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
  var x=(i)=>{
scannedItem=foods[i];

  }
return foods[scannedItem];



}

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

Access Property Names with Bracket Notation
#2

Your solution works, but

var x=(i)=>{ scannedItem=foods[i];  }

Makes no sense, and as it’s never called doesn’t do anything at all. Deleting that gives you the solution, I’m not sure you quite understand what you’re doing here, I’m having trouble following your logic.


#3

i am not a js expert but its provides a parameter’i’ that i can use to define as keys inside object food. because we are passing food[Objectkey] to get answer .


#4

Nope, it does not. That function returns undefined, it definitely does not do what you think it does. return foods[scannedItem]; is the only line necessary


#5

damn you’re right can you explain me what just happen inside this function i mean i get this that scannedItems == apples, oranges etc but i need further explanation


#6

foods is an object. So if you do foods['apples'] it looks up the value for apples on foods.


#7

Expanding on @DanCouper’s last post.

scannedItem represents the argument value passed into the function. If the value ‘apples’ is passed into the function, then foods[scannedItem] is foods[‘apples’] which returns the value 25 for the ‘apples’ property in the foods object.

Hopefully what I have added here helps instead of creating more confusion.


#8

Look at the starting of the thread, lemme know which this is wrong in that.


#9

I moved your posts to a new topic, because it needs to be addressed separately than the original thread’s question(s).

Can you ask your question again and post the code your are asking “which this is wrong in that”?


#10
var x=(i)=>{
scannedItem=foods[i];

Here i tried to get a food(parameters)= scannedItem , so is it what i am explaining?


#11

As @DanCouper already explained, all you have done is defined assigned a function to the variable x which attempts to assign foods[i] to a variable named scannedItem. You never call x, so nothing happens.


#12

Oh okay i think i need to learn more about data structure. Thank you.