Converting an object to a string

2018-12-31 17:03发布

How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)

Output:

Object { a=1, b=2} // very nice readable output :)
Item: [object Object] // no idea what's inside :(

30条回答
心情的温度
2楼-- · 2018-12-31 17:34

For non-nested objects:

Object.entries(o).map(x=>x.join(":")).join("\r\n")
查看更多
看风景的人
3楼-- · 2018-12-31 17:36

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);
查看更多
大哥的爱人
4楼-- · 2018-12-31 17:36

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 (obj.hasOwnProperty(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.

查看更多
栀子花@的思念
5楼-- · 2018-12-31 17:36
var o = {a:1, b:2};

o.toString=function(){
  return 'a='+this.a+', b='+this.b;
};

console.log(o);
console.log('Item: ' + o);

Since Javascript v1.0 works everywhere (even IE) this is a native approach and allows for a very costomised look of your object while debugging and in production https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

Usefull example

var Ship=function(n,x,y){
  this.name = n;
  this.x = x;
  this.y = y;
};
Ship.prototype.toString=function(){
  return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y;
};

alert([new Ship('Star Destroyer', 50.001, 53.201),
new Ship('Millennium Falcon', 123.987, 287.543),
new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
//"Star Destroyer" located at: x:50.001 y:53.201
//"Millennium Falcon" located at: x:123.987 y:287.543
//"TIE fighter" located at: x:83.06 y:102.523

Also, as a bonus

function ISO8601Date(){
  return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
}
var d=new Date();
d.toString=ISO8601Date;//demonstrates altering native object behaviour
alert(d);
//IE6   Fri Jul 29 04:21:26 UTC+1200 2016
//FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
//d.toString=ISO8601Date; 2016-7-29
查看更多
路过你的时光
6楼-- · 2018-12-31 17:37

1.

JSON.stringify(o);

Item: {"a":"1", "b":"2"}

2.

var o = {a:1, b:2};
var b=[]; Object.keys(o).forEach(function(k){b.push(k+":"+o[k]);});
b="{"+b.join(', ')+"}";
console.log('Item: ' + b);

Item: {a:1, b:2}

查看更多
笑指拈花
7楼-- · 2018-12-31 17:39

I was looking for this, and wrote a deep recursive one with indentation :

function objToString(obj, ndeep) {
  if(obj == null){ return String(obj); }
  switch(typeof obj){
    case "string": return '"'+obj+'"';
    case "function": return obj.name || obj.toString();
    case "object":
      var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
      return '{['[+isArray] + Object.keys(obj).map(function(key){
           return '\n\t' + indent + key + ': ' + objToString(obj[key], (ndeep||1)+1);
         }).join(',') + '\n' + indent + '}]'[+isArray];
    default: return obj.toString();
  }
}

Usage : objToString({ a: 1, b: { c: "test" } })

查看更多
登录 后发表回答