Reputation: 7589
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:
prop1
into an expression so that I could use x.prop1
? eval
can solve this then how and why would eval create security problems in this case?Upvotes: 0
Views: 862
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 eval
ing 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
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