Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating json keys on the fly

I would like to create a json object to send as a post array, but I need to create the key on the fly

var id = $('#myInput').val();

var post = {
    'product[123]': 'myValue',     // this works fine - but isn't dynamic
    'product['+id+']': 'myValue'   // this does not work
}

Sending it in as a string works fine, but I get an issue when I want to make it more dynamic. Am I missing something really simple here, or am I trying to do something Javascript isn't supposed to do?

like image 877
Eruant Avatar asked Jun 14 '12 15:06

Eruant


1 Answers

(Note that this has nothing to do with JSON. You're not using JSON there, you're using an object initializer. JSON is a textual (not code) format, which is a subset of JavaScript's object initializer syntax.)

Do it outside the object initializer, using [] notation:

var id = $('#myInput').val();

var post = {};
post[product[id]] = 'myValue';

That will take the value (at runtime) of product[id] and use that as the key for the property. If you wanted the key to literally be product[123] when id is 123, you'd use this instead:

post['product[' + id + ']'] = 'myValue';

A more generic discussion:

var a = "foo";
var obj = {};
obj[a] = "bar";
console.log(obj.foo); // "bar"

JavaScript allows you to specify property keys in two ways: Using dotted notation and a literal (obj.foo), or using bracketed notation and a string (obj["foo"]). In the latter case, the string doesn't have to be a string literal, it can be the result of any expression.

like image 89
T.J. Crowder Avatar answered Nov 13 '22 13:11

T.J. Crowder