开发者

JavaScript object - add property without using eval?

I have a JavaScript object that I'd like to add some propertie开发者_如何学Cs 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?
    }
}


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.


You can access objects via object['someKey'] as well.


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"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜