0

I'm using a callback to create an object, which I'd like to parse. I'm able to parse the object when the name/value pair I've specified exists, but unable to identify when the name/value pair in my object is undefined.

JSON Object with name/value pair populated:

parseMe([{"item1" : "", "item2" : "", "item3" : [], "item4" : "content goes here"}]);

JSON Object with name/value parsed undefined:

parseMe([{"error" : "Not available"}]);

Parsing logic EX:

    var renderR="";
    function parseMe(data){
     renderR="";
    if(data[0].item4!="collapse") renderR=data[0].item4; 
//if name/value pair isn't equal to "collapse" render it.
    else if(data[0].item4==='undefined'){ 
    document.getElementById('div1').style.display='none'; 
//if name/value pair is undefined in object hide the div.
     }
    }
Eric Philmore
  • 97
  • 1
  • 1
  • 4

2 Answers2

1

You should be using typeof to check for the key being undefined.

   function parseMe(data){

        renderR="";

        if(data[0].item4!="collapse"){

            renderR=data[0].item4; 
            //if name/value pair isn't equal to "collapse" render it.

        }else if(typeof data[0].item4==="undefined"){ 

            document.getElementById('div1').style.display='none'; 
            //if name/value pair is undefined in object hide the div.

        } 
}
Tarang
  • 318
  • 1
  • 10
1

As noted in the comments above, the else if condition could be changed to typeof(...) === 'undefined' to make the method work. A more standard solution, however is to query the object's key values using the hasOwnProperty method, e.g.

} else if (data[0].hasOwnProperty('item4')) {

This check should really be done first off, before attempting to access the property via the dot notation or square braces. Furthermore, this will not traverse the prototype chain to determine inherited attributes but it will detect any attribute directly belonging to the object, which should be sufficient for raw object values and parsing logic such as this. So a final solution that includes restructuring of the code could either use the hasOwnProperty method or use the in operator and a switch statement, e.g.

for (var key in data[0]) {
    var value = data[0][key];
    switch (key) {
        case "item1":
            dosomething(value);
            break;
        case "item2":
            dosomethingelse(value);
            break;
        // etc...
    }
}
flatline
  • 42,083
  • 4
  • 31
  • 38