babb
babb

Reputation: 423

JavaScript - Building of JSON data structure - How to change key name with variable value

I am dynamically building a JSON data structure. My code works fine, but I have a problem, as I need to set the data up, then replace the key name.

I need to replace the key name below with one of my variables - the actual request type itself that I have stored in a variable.

I need to do this for the 'requestType' key below. It works fone for the values, but not for replacing the key name.

Below is my code:

// Create data array, used for building request message
var data = {
    requestType: { 
        item1 : null,
        item2 : null,
        item3 : null
    }
};

// Set the field array variables with data
$('input[name="item1"], [name="item2"], [name="item3"]').each(function(index) {
    if(index==0){
        data.requestType.item1 = this.value;
    } else if(index==1){
        data.requestType.item2 = this.value;
    } else if(index==2){
        data.requestType.item3 = this.value;
    }
}); 

Please help :)

Upvotes: 0

Views: 1213

Answers (1)

nnnnnn
nnnnnn

Reputation: 150010

If you're saying that requestType is a variable containing some other string then you'd use this syntax:

data[requestType].item1 = this.value;

The basic principle is:

data.somePropertyName
// is equivalent to
data["somePropertyName"] // note the quotes
// is equivalent to
requestType = "somePropertyName"
data[requestType]

If you're saying you want to change an existing property's name then:

data.newPropertyName = data.requestType;
delete data.requestType;

Combine with the above [] syntax as necessary.

By the way, what you're dealing with is not JSON, it's an object that you're creating via an object literal. JSON is always a string representation of data (usually used for data interchange purposes) with a syntax that looks like JavaScript's object literal syntax.

Upvotes: 4

Related Questions