Javascript strings to object
I have two strings, one a key and one a value, which I would like to turn into an object and concatenate in a loop. For example:
var data = {};
// loop starts here
var a_key = 'element';
var a_val = 'value';
var a_obj = // somehow this equals { "element":"value" }
data = data.concat(a_obj);
// loop ends here
I'm just not sure how 开发者_JS百科to create an object from those two strings! Any help appreciated
You should be able to do:
var a_obj = new Object();
a_obj[a_key] = a_val
, no? (I'm not in a position to test this at the moment so take it with a pinch of salt...)
Doesn't really make sense to concatenate something to a object without a key. Perhaps data
should be an array of objects?
data = [];
a_obj = {};
a_obj[a_key] = a_val;
data += a_obj;
var a_key = 'key';
var a_val = 'value';
var a_obj = {};
a_obj[a_key] = a_val;
Note:
var a_obj = {}
and
var a_obj = new Object();
are the same, but {} feels cleaner and is recommended by Douglas Crockford's JSLint.
For appending objects to other objects, you could do something like... (not tested)
for (var key in a_obj) {
if (a_obj.hasOwnProperty(key)) { // avoid inherited properties
data[key] = a_obj[key];
}
}
var a_key = 'element';
var a_val = 'value';
var a_obj = {a_key:a_val};
精彩评论