I find myself making (potentially) more work for myself, by having to specify each dynamic key one line at a time.
What I am doing now to add additional keys to an existing object:
create_request[('title_' + id)] = field_data[0];
create_request[('field_' + id)] = field_data[1];
What I was hoping to be able to do is something like:
jQuery.extend({('title_' + id) : field_data[0], ('field_' + id) : field_data[1]});
Is there an easier way than what I am doing now (since what I was hoping would work doesn’t)? Or is this just a limitation of the language?
Edit for clarity:
Okay, so you can create an object in javascript like this:
{
a : 1
}
But that assumes that a is the string value for the key. What if I wanted the key to be the value of a variable?
I could do:
the_object[variable] = 1
But what if I wanted to do more than one of these dynamic insertions into the object? Is there a convenient way to do that?
If I could change just one thing about JavaScript, it would be object literal syntax. I think the property names should be evaluated as expressions the same as the property values; I think the benefits of this would outway the nuisance of being forced to include quoted property names when using static names. But, if wishes were fishes…
Using the square-bracket notation is the only built-in way to set properties with dynamic names, but it is not difficult to create your own function that takes input very similar to the syntax you hoped to use:
By using an array rather than a plain object to hold the new property names and values you can use dynamic names.
(Note also that even with the square-bracket syntax in your question you’ve made it slightly more complicated than it needs to be by including redundant parentheses.)