bsr
bsr

Reputation: 58662

Javascript object from string property and values

Is it possible to create a property based on string values.

I have a Json object, which used to fill the UI (select box).

"Conf" :{
    "Color":[
        {
            "Value":"BLUE"
        },
        {
            "Value":"GOLD"
        }   
    ],
    "Size":[
        {
            "Value":"12"
        },
        {
            "Value":"11"
        }
    ],
}

Based on the selection, I need to add it to an object (Item.Conf below). addSel provides the selection type (Color, Size etc), and the value (BLUE, 11 etc). How can I add the selection as shown below. So if the choice is Color : BLUE, I need to add it as Item.Conf[0].Color.Value = "BLUE" Is it possible?

Item = {
    Conf: [],
    addSel: function(type, val){ //for example type="Size", val = "11"

        //.... need to selection to Conf 
        // add a member "Size" from type string
        //set its value as val
        console.log(Conf[0].Size.Value) //=> 11
    }
}

In essence is it possible to make an object like

"Size":{
    "Value": 11
}

from strings

Upvotes: 0

Views: 109

Answers (1)

jfriend00
jfriend00

Reputation: 707258

Your question is not entirely clear for what exactly you're trying to do, but perhaps you just need to know about using the [variable] syntax to address a property name using a string.

Example:

var x = {};
var propName = "Value";
x[propName] = 11;

This is equivalent to:

var x = {};
x.Value = 11;

But, the first form allows the property name to be a string in a variable that is not known at the time you write the code whereas the second form can only be used when the property name is known ahead of time.

Upvotes: 1

Related Questions