Reputation:
I couldn't add the variable value as my key name in backbone.js is there any way to do this ?? look at the code below
(function ($) {
Today = Backbone.Model.extend({
});
var data= ['a','b','c'];
for(var i=0;i<data.length;i++){
today.set({i:data[i]});
}
} (jQuery));
how i am able to do that ?
Upvotes: 1
Views: 1620
Reputation: 123443
You should be able to simply pass data
to today.set()
.
var data = ['a','b','c'];
var today = new Today();
today.set(data);
console.log(today.attributes);
// {0: "a", 1: "b", 2: "c"}
Though, to explain the problem: Identifiers on the left-hand of :
in Object literals always become the key's name themselves. To use a variable's value as a key, you have to use bracket member operators.
var tmp = {};
tmp[i] = data[i];
today.set(tmp);
Upvotes: 4
Reputation: 146014
So in javascript an object literal with unquoted key uses the string version of that key:
var i=1;
var obj = {i: "this sets obj.i to this string, not obj['1']"};
If you want a computed key, follow this pattern:
var keyname = i + 'whatever' + 42;
var obj = {};
obj[keyname] = value;
Upvotes: 0