Comprobar si existe una clave dentro de un objeto json


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

El anterior es el objeto JSON con el que estoy tratando. Quiero comprobar si existe la clave 'merchant_id'. Probé el siguiente código, pero no funciona. ¿Alguna forma de lograrlo?

<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>
Author: jwpfox, 2013-12-27

7 answers

Prueba esto,

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

}

El objeto JS thisSession debe ser como

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

Puedes encontrar los detalles aquí

 425
Author: Anand Jha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-27 16:44:08

Hay varias maneras de hacerlo, dependiendo de tu intención.

thisSession.hasOwnProperty('merchant_id'); le dirá si esta sesión tiene esa clave en sí (es decir, no algo que hereda de otro lugar)

"merchant_id" in thisSession le dirá si esta sesión tiene la llave en absoluto, independientemente de dónde la obtuvo.

thisSession["merchant_id"] devolverá false si la clave no existe, o si su valor se evalúa como false por cualquier razón (por ejemplo, si es un literal false o el entero 0 y así sucesivamente).

 56
Author: Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-27 16:45:48

Type check también funcionará como:

if(typeof Obj.property == "undefined"){
    // Assign value to the property here
    Obj.property = someValue;
}
 6
Author: Kailas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-06 11:05:15

Solo quería señalar esto a pesar de que llego tarde a la fiesta. La pregunta original que estabas tratando de encontrar un 'No EN' esencialmente que parece no es compatible con la investigación (2 enlaces a continuación) que estaba haciendo. Así que si usted quería hacer un no:

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

Yo recomendaría simplemente estableciendo esa expresión = = a lo que estás buscando para

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

 5
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-07 16:08:31

Función para comprobar objetos indefinidos y nulos

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

Aquí hay una manera fácil de comprobar si el objeto enviado es contain undefined o 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");
)
 0
Author: sai sanath,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-16 06:09:47

¿Qué pasa con esto?

if (thisSession.merchant_id){
   ...
}

Es mucho más simple que las soluciones anteriores.

 0
Author: Agustí Sánchez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-18 16:08:11

Puedes probar if(typeof object !== 'undefined')

 -10
Author: Zonger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-06 10:15:09