yogi
yogi

Reputation: 19619

Converting string to javascript object

I want my user to input some text in an input field and click a button "Evaluate" on clicking that button I will convert that inputted text into a JavaScript object if I could and will show all of it's members(properties and functions).

For example if user inputs "document" or "window" I will show all members of document and window respectively.

Iterating through the members of an object is done, but when user inputs some text in input text field and I get that text than that value is treated as String of course how can I convert that text into an object like "document" to document and "window" to window ???

Upvotes: 0

Views: 2899

Answers (4)

Ider
Ider

Reputation: 11

If your string is JSON format, or the string is a name of javascript object, here a way I saw jQuery.parseJSON do to convert string to object.

var s2o = (new Function("return " +val+";"))();

suppose val contains the value from text input.

It's kind like using Function object as 'compiler', so that you get return a javascript object.

If user pass in document, it give out document object;
if user pass in {id:1, name:"test"}, it give out that object.

Upvotes: 0

Vlad Ciobanu
Vlad Ciobanu

Reputation: 1483

The proposed solution won't work for sub-properties (ex. window.document.body). I've written a small jsFiddle that should work for most cases. It certainly lacks real error checks but should be a decent place to start http://jsfiddle.net/a6A4m/1/

 var showProperties = function(text) {
        var output = '';
        var object = window;

        // if it isn't the global window object
        if (text !== 'window') {
            var parts = text.split('.');

            // Since we're using pop, we need to reverse it first.
            parts = parts.reverse();

            while (parts.length > 0) {
                object = object[parts.pop()];
            }
        }

        $('#content').html(getOutput(object));
    };

Upvotes: 1

McGarnagle
McGarnagle

Reputation: 102793

You can use "eval". Edit: Thanks to the comments of @Victor and @Cerbrus for pointing out that eval is unnecessary here. You can also use window[input].

var input = "document";
var obj = eval(input);
for (var prop in obj) console.log(prop + ": " + obj[prop]);

If it's a member of another object (ie, a global object), then you can use the bracket-notation:

var hello = "world";
var variableName = "hello";
console.log(JSON.stringify(window[variableName]));

Upvotes: 3

Maxim Pechenin
Maxim Pechenin

Reputation: 344

If you getting input value like that

var selector = $('input').val();

Then the object will be

$(selector)

Upvotes: 0

Related Questions