Check if a key exists inside a JSON object

JavascriptJson

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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).

Solution 3 - Javascript

(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 is not supported from 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 just setting that expression == to what you're looking for

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in http://www.w3schools.com/jsref/jsref_operators.asp

Solution 4 - Javascript

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!');
}

Solution 5 - Javascript

Type check also works :

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

Solution 6 - Javascript

This code causes esLint issue: no-prototype-builtins

foo.hasOwnProperty("bar") 

The suggest way here is:

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

Solution 7 - Javascript

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");

Solution 8 - Javascript

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");
)

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAjeeshView Question on Stackoverflow
Solution 1 - JavascriptAnand JhaView Answer on Stackoverflow
Solution 2 - JavascriptPaulView Answer on Stackoverflow
Solution 3 - JavascriptSamView Answer on Stackoverflow
Solution 4 - Javascriptcode2heavenView Answer on Stackoverflow
Solution 5 - JavascriptKailasView Answer on Stackoverflow
Solution 6 - JavascriptSyedView Answer on Stackoverflow
Solution 7 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 8 - Javascriptsai sanathView Answer on Stackoverflow
Solution 9 - JavascriptZongerView Answer on Stackoverflow