user31782
user31782

Reputation: 7589

How to convert string into object property?

I have a json data that has unknown objects like this:

var x = {
  "unknown1": 234,
  "unknown2": 324
}

I can get the properties name as:

var prop1 = Object.keys(x)[0];  

Now I want to find the value of this property. I can obviously do x[prop1], but I wanted to do x.prop1. My question is:

Upvotes: 0

Views: 862

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074228

What are ways to convert prop1 into an expression so that I could use x.prop1?

You can't, without generating source code and compiling/evaluating it.

If eval can solve this then how and why would eval create security problems in this case?

Yes, eval (and its close cousin new Function) can do this. It's only a security issue if what you're evaling comes from an untrusted source. If you can trust that the value of prop1 doesn't contain malicious content, then you can use eval("x." + prop1) to do this. Or new Function("x", "return x." + prop1)(x).

But there's no good reason to. Just use x[prop1]. That's what brackets notation is for. It's normal practice, it doesn't have to fire up a parser and code generator, it's faster, and you don't have to worry about prop1 having malicious code in it. If you use eval or new Function, it's not normal practice, it has to fire up a parser and code generator, it's slower, and you have that niggling concern in the back of your mind. So use x[prop1]. :-)

Upvotes: 4

William Comartin
William Comartin

Reputation: 1

As @mhodges says in his comment you could add a new property.

but it might seem redundant to do so.

x.prop1 = x[Object.keys(x)[0]]

Upvotes: 0

Related Questions