AP257
AP257

Reputation: 93793

JavaScript object - add property without using eval?

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

Answers (3)

Tauren
Tauren

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

BGerrissen
BGerrissen

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

jwueller
jwueller

Reputation: 30996

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

Upvotes: 1

Related Questions