0

I'm making a function that will count through data food amount.

const countFood = (foodType) => {
  let foodNeeded = 0;

  if (animal.food.type === foodType) {
    foodNeeded += +animal.food.amount;
  };

  const food = foodType;

  if (foodNeeded > (pavilion.food[food] - 1)) return true;

  countFood(foodType);
}

countFood('meat');

It's a piece of code in for loop.

I need use this argument to request it like pavilion.food.meat

a1tern4tive
  • 422
  • 3
  • 11
  • Not getting this properly.How is `foodType` related to `pavilion.food.meat`? and what does this means `(pavilion.food->>[food]<<- - 1)`? – palaѕн Jun 03 '20 at 04:47
  • 1
    Does this answer your question? [Accessing property of object with variable](https://stackoverflow.com/questions/11230063/accessing-property-of-object-with-variable) – user120242 Jun 03 '20 at 04:50
  • Just remove the `->>` and `<<-` because the `[food]` syntax is already correct – slebetman Jun 03 '20 at 04:51
  • OK. As written there is no question because the code should be working. Do you have any other issue with it apart from the original `I need to use this argument` question that you accidentally answered yourself? – slebetman Jun 03 '20 at 04:53
  • It works. Thanks to all! – a1tern4tive Jun 03 '20 at 05:00

2 Answers2

1

You can access an object property using the bracket notation.

Example:

const pavillon = {
  food: {
    meat: 3
  }
}

function getFood(foodType) {
  const food = pavillon.food[foodType]
  
  console.log(food)
  
  return food
}

getFood('meat');
Erazihel
  • 7,295
  • 6
  • 30
  • 53
1

If you have:

{
  pavilion: {
    food: {
      meat: {...}
    }
  }
}

Then you can use pavilion.food['meat'] to reference the inner object.

More generally, pavilion.food[foodType].