Reputation: 93793
I have a JavaScript object that I'd like to add some properties to, but I don't know what the names of the properties are until runtime.
Can I do this without using eval? If so, how?
var get_params = new Object();
var params = {'name':'john', 'age':'23'}; //actually not known until runtime
for (var i=0, len=params.length; i<len; ++i ){
get_params.p[0] = p[1]; //How can I set p[0] as the object property?
}
}
Upvotes: 1
Views: 2890
Reputation: 27235
var get_params = {};
var params = [{'name':'john'}, {'age':'23'}];
for (var i=0,len=params.length; i<len; ++i){
for (var p in params[i]) {
if(params[i].hasOwnProperty(p)) {
get_params[p] = params[i][p];
}
}
}
Ok, that's my third version. I think it will do what I understand you to desire. Kind of convoluted however, and there are probably better formats for your dynamic array. If I understand what you want to do correctly, this should work. Basically, it creates the following object:
get_params = {
name: "john",
age: "23"
}
Upvotes: 0
Reputation: 21680
Since your code example has a malformed array, I will include 2 variations.
Variation 1 (params is an actual object and not an array):
var get_params = {}; // prefer literal over Object constructors.
var params = {'name':'john', 'age':'23'}; // @runtime (as object literal)
for (var key in params){
if(params.hasOwnProperty(key)) { // so we dont copy native props
get_params[key] = params[key];
}
}
Variation 2 (param is an array containing objects):
var get_params = {}; // prefer literal over Object constructors.
var params = [{'name':'john'},{'age':'23'}]; // @runtime (as array literal)
for(var i=0,param;param=params[i];i++) {
for (var key in param){
if(param.hasOwnProperty(key)) {
get_params[key] = param[key];
}
}
}
Enjoy.
Upvotes: 1