Preamas Preamas - 1 year ago 74
Javascript Question

Javascript array to JSON array, returns array but puts undefined infront

var ORDER = {"Rows":[]};

var data = [];
data[0] = ["0","V",amount[a],valueThree,"","",prcat,"00001","",price,"",Descr];
var dataJSONstring = JSON.stringify(data);
ORDER.Rows[0] += dataJSONstring;

I'm trying to place the Javascript data array as an array into the JSON "Rows" array. I've tried to stringify it, but whenever I do it does put it into a JSON array, but returns: **


How to remove the "undefined"? Can't find out how to do it, any ideas?

Answer Source

It returns undefined + string, which is what I don't understand

Because ORDER.Rows[0] is undefined. You've set Rows to an empty array. It has no entry at index 0. So retrieving that entry gives you undefined, which when you join it with a string via + is converted to "undefined" (plus the string).

Remember that a += b is effectively a = a + b (but without evaluating a twice). So your code is effectively

ORDER.Rows[0] = ORDER.Rows[0] + dataJSONstring;

If you wanted to store the string there, you didn't want +=, just =:

ORDER.Rows[0] = dataJSONstring;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download