2

I need to learn how to pass an associative array to a function so that I could do the following within the function:

function someName($argums) {
    if (gettype($argums) != 'array' || 
       !array_key_exists('myOneKey', $argums) ||
       !array_key_exists('myOtherKey', $argums)) {              
           return false;
    } 

    /*do other stuff*/
}

(That's how I would do it in PHP that I am looking for in JavaScript.)

1 Answer 1

6

All Javascript objects are associative arrays, so this is really easy. You actually have a few options, because an object can have properties of its own, properties it inherits from its prototype object, properties with undefined values, and properties with "falsey" values (undefined, null, 0, "", or of course, false). (There's a difference between an object not having a property and having one with an undefined value.)

Checking to see if the object has the properties itself: You use obj.hasOwnProperty:

function someName(obj) {
    if (!obj ||
        !obj.hasOwnProperty('myOneKey') ||
        !obj.hasOwnProperty('myOtherKey'))
        return false;
    }
    // Do other stuff
}

Checking to see if the object has the property itself or via its prototype: You use propName in obj:

function someName(obj) {
    if (!obj ||
        !('myOneKey' in obj) ||
        !('myOtherKey' in obj))
        return false;
    }
    // Do other stuff
}

Checking to see if the object has the property (directly, or via prototype) and it's not undefined: You look for an undefined value:

function someName(obj) {
    if (!obj ||
        typeof obj.myOneKey === "undefined" ||
        typeof obj.myOtherKey === "undefined")
        return false;
    }
    // Do other stuff
}

Checking to see if the property is falsey (undefined, null, 0, "", or of course, false), regardless of why: Just use !:

function someName(obj) {
    if (!obj ||
        !obj.myOneKey ||
        !obj.myOtherKey)
        return false;
    }
    // Do other stuff
}

Regardless, usage:

var obj = {
    myOneKey: 'fred',
    myOtherKey: 'barney'
};
someName(obj);
Sign up to request clarification or add additional context in comments.

4 Comments

And how would I call that function with such arguments?
And can't I use the in operator instead of hasOwnProperty?
@dfjhdfjhdf: I was adding a discussion of that and the distinction between them as you were asking the question, apparently. :-)
+1 - Great answer for including all the FAQs that come along with this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.