Converting an object to a string Converting an object to a string javascript javascript

Converting an object to a string


I would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string. Most modern browsers support this method natively, but for those that don't, you can include a JS version:

var obj = {  name: 'myObj'};JSON.stringify(obj);


Use javascript String() function

 String(yourobject); //returns [object Object]

or stringify()

JSON.stringify(yourobject)


Sure, to convert an object into a string, you either have to use your own method, such as:

function objToString (obj) {    var str = '';    for (var p in obj) {        if (Object.prototype.hasOwnProperty.call(obj, p)) {            str += p + '::' + obj[p] + '\n';        }    }    return str;}

Actually, the above just shows the general approach; you may wish to use something like http://phpjs.org/functions/var_export:578 or http://phpjs.org/functions/var_dump:604

or, if you are not using methods (functions as properties of your object), you may be able to use the new standard (but not implemented in older browsers, though you can find a utility to help with it for them too), JSON.stringify(). But again, that won't work if the object uses functions or other properties which aren't serializable to JSON.

Update:

A more modern solution would be:

function objToString (obj) {    let str = '';    for (const [p, val] of Object.entries(obj)) {        str += `${p}::${val}\n`;    }    return str;}

or:

function objToString (obj) {    return Object.entries(obj).reduce((str, [p, val]) => {        return `${str}${p}::${val}\n`;    }, '');}