javascript - How to preserve hasOwnProperty on JSON.parsed responseText? -


i new developer working on simple application part of training process - gentle.

i have built function in javascript accepts arbitrary objects elsewhere , builds legal post request string.

code:

    function postify(opost){     var out = '';     (key in opost){         if (opost.hasownproperty(key) && key >0){             if(opost[key].value != 'submit'){                 out += '&' + opost[key].name + '=' + opost[key].value;             }         }     }     return out; } 

there many it, 1 mine. elected use hasownproperty conditional, total list of inherited properties quite long.

one of objects pass function json parsed responsetext object, retrieved so.

function postdata(str){         var http = new xmlhttprequest();         http.open('post', 'test.php',false);         http.setrequestheader("content-type", "application/x-www-form-urlencoded");         http.setrequestheader("content-length", str.length);         http.setrequestheader("connection", "close");         http.send(str);         var response = json.parse(http.responsetext);         responsehandle(response);     } 

so, problem - both of these functions supposed do, until responsehandle function routes response object postify function. manual checking indicates expected properties in place, postify() won't concatenate string because properties seem have been inherited.

i aware trivially brute force assign necessary properties - handler function needed either way. aware synchronous xmlhttprequest deprecated - right second, it's need, , works fine.

so, then, questions - there way pass json.parsed object such hasownproperty() == true maintained? there different property or technique or should using in postify() deliberately set key value pairs? should rig post transmit of inherited properties of object posting php?

the problem isn't hasownproperty, it's key > 0. unless opost array, keys strings. when compare string number, string converted number. if string isn't numeric, conversion return nan, , comparing 0 false.

your function shouldn't have worked object, doesn't matter if came json.parse(). when json.parse returns object, properties "own".

the fix change

if (opost.hasownproperty(key) && key >0){ 

to

if (opost.hasownproperty(key)){ 

Comments