Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: get all object parameters

I have a JS object with a variable number of parameters. Is there a way to see what parameters have been passed this particular time?

The example:

function getElement() {
    var scope = document;

    this.by = function(data){
        if (data.id)    scope = scope.getElementById(data.id);
        if (data.tag)   scope = scope.getElementsByTagName(data.tag);       
        return scope;
    }
}

And I run it like so

var x = new getElement(); 
vad div = x.by({id : "chosenID"});

gets the div with the id chosenID

or

var x = new getElement(); 
vad inputs = x.by({id : "chosenID", tag : "input"});

gets all the inputs in the div with the id chosenID;

I want to know if I passed one or two parameters, and which ones.

Thanks!

ps: I appreciate your time in helping me out, but please do not sugget jQuery or other JS framework as this is for learning purposes only. Much obliged, Sorin.

like image 309
Sorin Buturugeanu Avatar asked Jan 31 '11 21:01

Sorin Buturugeanu


People also ask

How do I get all the values of an object?

values() Method: The Object. values() method is used to return an array of the object's own enumerable property values. The array can be looped using a for-loop to get all the values of the object.

How can you get the list of all properties in an object in JavaScript?

getOwnPropertyNames() The Object. getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.


2 Answers

Use a for … in loop to iterate over the passed object's parameters, like:

var prop;

for (prop in data) {
    if (data.hasOwnProperty(prop)) {
        // do something with data[prop]
    }
}

Don't forget to check the property with hasOwnProperty.

like image 145
Marcel Korpel Avatar answered Oct 14 '22 19:10

Marcel Korpel


Using object iteration (key in data) and array-combining... you can return a number of elements... although the object iteration is rendered pretty useless by by the switch statement.

function getElement() {
    var scope = document;
    this.by = function(data){
        var key;
        var ret=[];
        for (key in data) {
          if(data.hasOwnProperty(key)) {
            switch(key) {
              case "id":
                ret=ret.concat(scope.getElementById(data[key]));
                break;
              case "tag":
                ret=ret.concat(scope.getElementsByTagName(data[key]));
                break;
              default:
                throw new Error("Unknown property "+key);
            }
          }
        }
        return ret;
    };
}
like image 31
Rudu Avatar answered Oct 14 '22 19:10

Rudu