0

I have a global object with various properties whose values are strings. When a user types a string into an HTML input, I'm using javascript to assign that string to a variable. I need to convert that string to a property name and return the string associated with that property.

For example:

myglobalobject = {

    propertyname : "String value to be returned."

}

function GetInput(){
    mystring = document.getElementById('input').value;

    myproperty = convertstringToProperty(str); //This is where I need a solution

    return myglobalobject.myproperty;
}
Truth
  • 486
  • 7
  • 19

3 Answers3

3

Well, properties can be accessed with, you guess it, a string:

const myObject = {
  property1: 0,
  property2: 1,
};

const inputFromUser = 'property1';
console.log(myObject[inputFromUser]);
3

Just use a computed property:

return myglobalobject[mystring];

This is a generalization of the fact that property accesses using dot notation are the same as accessing with brackets and a string literal:

obj.prop === obj["prop"];

So when you have something that isn't a string literal, just use the bracket notation.

Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
0

You don't even need a function:

var myglobalobject = {
    propertyname : "String value to be returned."
}
function GetInput(){
    mystring = 'anotherKey';

    return myglobalobject[mystring] = undefined;
}
GetInput()
console.log(myglobalobject)
guijob
  • 4,413
  • 3
  • 20
  • 39