node.jsconsole.logobject-property

Node.js how do you console.log out an object-property + variable?


I am trying to console.log out an true / false statement by adding a variable to the end of the objectProperty to select the property: (appleAmount.amount+number)? How do you do it?

let apple = 48;
let appleAmount = {
  amount0 : 20,
  amount1 : 40,
  amount2 : 48
}

let number = 2;
console.log(apple === appleAmount.amount+number);

Solution

  • In JavaScript, you can access properties by their string name, not just through the dot operator:

    console.log(apple === appleAmount[`amount${number}`]); // If your version supports interpolation
    console.log(apple === appleAmount['amount' + number]);