SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Returning object property names

    Is is possible to return just the names of each property of an object. For example, give this object:

    my_object = function () {
    this.param_1 = 'whatever';
    this.param_2 = "something_else";
    this.param_3 = new other_object();
    };

    I can do my_object.toSource() to get entire thing in the form of a string, but then I would have to parse the string to get the parameter names. I'll fall back on that if I need to, but I'd like a more elegant solution if possible. I can use a for/in loop to get each of the values and the child object names, but it won't return the names child string or anything like that. I'd like to find something that will just return the strings "param_1", "param_2", "param_3". I've been using some jQuery in the script as well, so anything using jQuery would work too.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,678
    Mentioned
    99 Post(s)
    Tagged
    4 Thread(s)
    If you define it using object notation then it's a piece of cake.

    Code javascript:
    function other_object2() {
    }
    my_object = {
    	param_1: 'whatever',
    	param_2: "something_else",
    	param_3: new other_object2()
    };
    for (each in my_object) {
    	console.log(each);
    }
    // output:
    // param_1
    // param_2
    // param_3

    When you assign properties on to the function itself, you will need to create a new instance of that function to easily see what's there.

    Code javascript:
    function other_object() {
    }
    my_object2 = function () {
    	this.param_1 = 'whatever',
    	this.param_2 = "something_else",
    	this.param_3 = new other_object()
    };
    var testObject = new my_object2;
    for (each in testObject) {
    	console.log(each);
    }
    // output:
    // param_1
    // param_2
    // param_3
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Holy !@$#! It wasn't the notation I was using, it was that my for in loop was setup like this:

    for (each in my_object) {
    console.log(my_object[each]);
    }

    instead of:

    for (each in my_object) {
    console.log(each);
    }

    I don't know why I didn't notice that before, I'm retarded. Thanks for the help even if it fixed my problem for a different reason.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •