David Fernandez
David Fernandez

Reputation: 175

String variable name to JSON

I have two variables like this:

var test = {"1":"test","2":"test2"};
var isdefined = "test.1"

How can I check isdefined variable is not 'undefined'?

Thanks!

Upvotes: 1

Views: 123

Answers (3)

Onur Topal
Onur Topal

Reputation: 3061

The answer of your question is No and Yes,

No, because if your object property starts with a number or it is a number you cannot access it using objectName.12 it is a rule you cannot change and in your case it is a number

on the other hand it is Yes, if your object defined properly you can do it please check the below code block;

var test = {"1":"test","_2":"test2"};
var isdefined = "test._2";
alert(eval(isdefined)); // will return test2
alert(eval("test.1"));  // throws exception.

Upvotes: 1

nbrooks
nbrooks

Reputation: 18233

JavaScript undefined evaluates to false, so you can simply do:

if ( isdefined ) {
    // do stuff
}

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129792

Are you trying to test if 1 exists in test? In that case, you could do

test.hasOwnProperty('1')

Upvotes: 1

Related Questions