antonjs
antonjs

Reputation: 14318

About the limitation of the literal object syntax

I know that the limitation of the literal object syntax is that the names has to be literal.

By the way I need to accomplish the following task, which way do you recommend me?

I have an object obj1 which I want traverse and then pass to another function which accept only literal object like parameter.

I wrote just the basic example to get the basic idea of what I am asking.

The problem is on the last loop, see the inline comments.

obj1 = {k1 : 1} // simple literal object

fn = function (json) {
    // this function can accept just  literal object 
    console.log("result: ", json); // {key : true}, but I want {k1 : true}
}

for (key in obj1) {
    obj = [];
    fn ({
        key : true // I want the key to be k1 and not key
    })
};

Upvotes: 3

Views: 124

Answers (5)

YuS
YuS

Reputation: 2045

May be try this?

for (key in obj1) {
  var obj = {};
  obj[key] = true;
  fn (obj);
};

Upvotes: 0

Quentin
Quentin

Reputation: 943605

another function which accept only literal object like parameter.

There's no such thing. Outside of the moment it is created, there is no difference between an object created using a literal and one created some other way.

for (key in obj1) {
    obj = [];
    var foo = {};
    foo[key] = true;
    fn (foo);
};

Upvotes: 1

Thilo
Thilo

Reputation: 262534

 // this function can accept just  literal object 

No. The function does not care how the parameter object was constructed.

You can do

 obj = {};
 key = "k1";
 obj[key] = true;
 fn(obj);

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359836

Use bracket notation to use a variable as a key.

function fn(obj) {
    console.log("result: ", obj);
}

for (var key in obj1) {
    var temp = {};
    temp[key] = true;
    fn (temp);
};

Also note the use of var (so you don't create globally-scope variables) and the different style function declaration.

Upvotes: 1

alex
alex

Reputation: 490283

Just do this...

var obj = {};
obj[key] = true;
fn(obj);

That is about as elegant as you will get. Please do not use eval().

Upvotes: 2

Related Questions