There are many good general answers, but think about it:
So, instead, I will talk about some specific cases. First, I usually start with:
function f (x) { x = x || {}
It also sets the context for the following.
My usual approach is to simply check the value of true-y. True value means "delivered." However, this has the disadvantage that it does not process 0 or "as is".
if (x.id) { // x.id is any truth-y }
If 0 is the accepted input, then I am expanding the check so that the values ββare not undefined considered to be "delivered." The unset property is always undefined by default. (This method will accept all true-y and false-y values, such as 0, "", and null ).
if (x.id !== undefined) { // x.id is all truth-y and all-but-undefined false-y }
If undefined is an accepted input (which I would strongly oppose), then the check can be based on hasOwnProperty . This has the disadvantage of not checking the [[prototype]] chain.
if (x.hasOwnProperty("id")) { // x.id set to something, including undefined }
The for(..in..) construct can also be used to iterate over properties of an object (including properties in [[prototype]] , unless they are specifically hidden). However, for the general case of handling input (for example, not creating a JSON library), I find it simple and clean to deal with properties on the input object (s) in one of the methods described above.
user166390
source share