0

When we concatenate a string to an object, it automatically converts all the values into string.

Is there a way where it is not converted to a string or the string can be converted back to a statement.

I'm trying to do something like if I type length, it adds together to the string variable and counts the length of the string.

var property = prompt("Add the Property");
var myObject = "This is the String";
var propertyCombinedWithObject = myObject + "." + property;
console.log(propertyCombinedWithObject);

The result is a string "This is the String".length rather than counting the numbers of the string.

I have tried

eval(propertyCombinedWithObject)

but it doesn't work.

dante
  • 31
  • 4
  • prototype function will do the same as you asking – sumeet kumar Sep 01 '15 at 21:53
  • @bergi, thanks for pointing out that it is a duplicate question. I think it's a different question. Though we may have the same answer, but I wouldn't understand that question relating to my question. Thank you. – dante Sep 01 '15 at 22:06

2 Answers2

2

To access a property of an object, you can use the square bracket notation:

var property = prompt("Add the Property");
var myObject = "This is the String";
var propertyCombinedWithObject = myObject[property];
console.log(propertyCombinedWithObject);
fstanis
  • 5,234
  • 1
  • 23
  • 42
0

Yes what you are looking for is JS-objects with bracket notation.

var property = prompt("Add the Property");
var myObject = "This is the String";
console.log(myObject[property]);
eljefedelrodeodeljefe
  • 6,304
  • 7
  • 29
  • 61