461
amt: "10.00"
email: "[email protected]"
merchant_id: "sam"
mobileNo: "9874563210"
orderID: "123456"
passkey: "1234"

The above is the JSON object I'm dealing with. I want to check if the merchant_id key exists. I tried the below code, but it's not working. Any way to achieve it?

<script>
window.onload = function getApp()
{
  var thisSession = JSON.parse('<?php echo json_encode($_POST); ?>');
  //console.log(thisSession);
  if (!("merchant_id" in thisSession)==0)
  {
    // do nothing.
  }
  else 
  {
    alert("yeah");
  }
}
</script>
8
  • What is the output of <?php echo json_encode($_POST); ?>? Commented Dec 27, 2013 at 16:36
  • Its out put is what I have shown at the top of my question,the json object Commented Dec 27, 2013 at 16:37
  • 1
    What is the output of console.log(thisSession);? Commented Dec 27, 2013 at 16:41
  • 2
    Also what is the benefit of using !("merchant_id" in thisSession)==0 where you can simply use "merchant_id" in thisSession? Commented Dec 27, 2013 at 16:42
  • 2
    Possible duplicate of Checking if a key exists in a JavaScript object? Commented Jun 26, 2016 at 3:45

11 Answers 11

790

Try this

if (thisSession.hasOwnProperty("merchant_id")) {

}

the JS Object thisSession should be like

{
  amt: "10.00",
  email: "[email protected]",
  merchant_id: "sam",
  mobileNo: "9874563210",
  orderID: "123456",
  passkey: "1234"
}

you can find the details here

Sign up to request clarification or add additional context in comments.

5 Comments

For edification, what, if any, is the difference between if(thisSession.merchant_id !== undefined) and if(thisSession.hasOwnProperty('merchant_id')) or is it doing the same thing behind the scenes?
@zero298, both are not same, using hasOwnProperty is safe ...more more details please check the link stackoverflow.com/questions/10895288/…
Eslint throws the error error Do not access Object.prototype method 'hasOwnProperty' from target object when using this method. Thoughts?
@hamncheez If JSON has 'hasOwnProperty' field, it will shadow the original func. Use Object.prototype.hasOwnProperty.call(thisSession, 'merchant_id')
2023 update: hasOwnProperty is no longer recommended (except to support older browsers). As I describe in this answer: stackoverflow.com/a/77656009/1261335 , if you are targeting modern browsers / node versions, that function is considered obsolete and you should prefer hasOwn.
110

There's several ways to do it, depending on your intent.

thisSession.hasOwnProperty('merchant_id'); will tell you if thisSession has that key itself (i.e. not something it inherits from elsewhere)

"merchant_id" in thisSession will tell you if thisSession has the key at all, regardless of where it got it.

thisSession["merchant_id"] will return false if the key does not exist, or if its value evaluates to false for any reason (e.g. if it's a literal false or the integer 0 and so on).

2 Comments

thisSession["merchant_id"] will return undefined not false.
Ok, "falsy" then.
43

(I wanted to point this out even though I'm late to the party)
The original question you were trying to find a 'Not IN' essentially. It looks like it is not supported by the research (2 links below) that I was doing.

So if you wanted to do a 'Not In':

    ("merchant_id" in x)
    true
    ("merchant_id_NotInObject" in x)
    false 

I'd recommend using the ! operator

    if (!("merchant_id" in thisSession))
    {
        // do nothing.
    }
    else 
    {
        alert("yeah");
    }

https://linuxhint.com/use-not-in-operator-javascript/

Comments

37

you can do like this:

if("merchant_id" in thisSession){ /** will return true if exist */
 console.log('Exist!');
}

or

if(thisSession["merchant_id"]){ /** will return its value if exist */
 console.log('Exist!');
}

2 Comments

Works perfect on Node
Note, the second option will not work for falsey values (e.g. null, undefined, 0).
27

Type check also works :

if(typeof Obj.property == "undefined"){
    // Assign value to the property here
    Obj.property = someValue;
}

Comments

16

This code causes esLint issue: no-prototype-builtins

foo.hasOwnProperty("bar") 

The suggest way here is:

Object.prototype.hasOwnProperty.call(foo, "bar");

Comments

9

I change your if statement slightly and works (also for inherited obj - look on snippet)

if(!("merchant_id" in thisSession)) alert("yeah");

var sessionA = {
  amt: "10.00",
  email: "[email protected]",
  merchant_id: "sam",
  mobileNo: "9874563210",
  orderID: "123456",
  passkey: "1234",
}

var sessionB = {
  amt: "10.00",
  email: "[email protected]",
  mobileNo: "9874563210",
  orderID: "123456",
  passkey: "1234",
}


var sessionCfromA = Object.create(sessionA); // inheritance
sessionCfromA.name = 'john';


if (!("merchant_id" in sessionA)) alert("merchant_id not in sessionA");
if (!("merchant_id" in sessionB)) alert("merchant_id not in sessionB");
if (!("merchant_id" in sessionCfromA)) alert("merchant_id not in sessionCfromA");

if ("merchant_id" in sessionA) alert("merchant_id in sessionA");
if ("merchant_id" in sessionB) alert("merchant_id in sessionB");
if ("merchant_id" in sessionCfromA) alert("merchant_id in sessionCfromA");

Comments

1

JavaScript changes once again!

(TL;DR: Use Object.hasOwn now.)

The long standing highest-voted answer recommends using hasOwnProperty. This was the best answer at the time, but it does have a number of tricky bits that can trip you up. For example, if the variable can be null, this will cause a TypeError when you attempt to call hasOwnProperty. Less commonly (but a symptom of the same problem), if an object could potentially have a key named "hasOwnProperty," that would shadow the function you wanted. (This could be a problem if, for example, you are parsing user-provided input.)

Because of all that, the previously correct way to call the function is this mess:

Object.prototype.hasOwnProperty.call(thisSession, "merchant_id");

In updated browsers and recent versions of node there is a new alternative that addresses these problems. Object now has a static method named hasOwn that addresses these pitfalls.

Object.hasOwn(thisSession, "merchant_id")

Ahh, much better. :)

If you are targeting browsers or node versions new enough to have hasOwn, you should stop using hasOwnProperty entirely. It is obsolete.

Comments

0

function to check undefined and null objects

function elementCheck(objarray, callback) {
        var list_undefined = "";
        async.forEachOf(objarray, function (item, key, next_key) {
            console.log("item----->", item);
            console.log("key----->", key);
            if (item == undefined || item == '') {
                list_undefined = list_undefined + "" + key + "!!  ";
                next_key(null);
            } else {
                next_key(null);
            }
        }, function (next_key) {
            callback(list_undefined);
        })
    }

here is an easy way to check whether object sent is contain undefined or null

var objarray={
"passenger_id":"59b64a2ad328b62e41f9050d",
"started_ride":"1",
"bus_id":"59b8f920e6f7b87b855393ca",
"route_id":"59b1333c36a6c342e132f5d5",
"start_location":"",
"stop_location":""
}
elementCheck(objarray,function(list){
console.log("list");
)

Comments

0

we can use lodash library

import _ from 'lodash';

if(_.isEmpty(merchant_id)){
    // do nothing
}
else{
    //do something with merchant id
}

Comments

-16

You can try if(typeof object !== 'undefined')

1 Comment

You can surely try, but it won't do much.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.