-1

Hello so basically I wonder how I can achieve to select property from object with:

objectName.someVariable.

For example how to make this code console.outing number from object:

var a = function(selected){
  console.log(selected);
    var q = {
    black: 1,
    red: 2,
    blue: 3
  }
  console.log(q.selected);
  console.log(q+'.'+selected);
}
BT101
  • 3,666
  • 10
  • 41
  • 90
  • 2
    This is currently very unclear. – Mitya Oct 22 '17 at 10:25
  • What is so unclear? Just take a look at code no words needed. – BT101 Oct 22 '17 at 10:32
  • @BT101 If it isn't unclear, why can't you figure it out yourself? – Dexygen Oct 22 '17 at 10:36
  • Possible duplicate of [Using a variable for a key in a JavaScript object literal](https://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) – RIYAJ KHAN Oct 22 '17 at 10:41
  • 1
    No words needed? So you honestly think SO is full of people who just read explanationless code and try to guess what the problem might be? If you want help, help us to help you. – Mitya Oct 22 '17 at 10:45

1 Answers1

1

You can access to an object property with:

  • a point like this: q.black
  • with two [] like this : q.["black"] or q.[aVariable] //aVariable = "black"

In your example, you can simply do like this:

var a = function(selected){
  console.log(selected);
    var q = {
    black: 1,
    red: 2,
    blue: 3
  }
  console.log(q.selected);  // Serve to nothing.
  console.log(q[selected]+'.'+selected);
}

You can consult w3schools if you want more details.

Tell me if you have some questions.

SphynxTech
  • 1,799
  • 2
  • 18
  • 38