如何将JavaScript对象转换为字符串?

例子:

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

输出:

对象{a=1, b=2} //非常好的可读输出:) Item: [object object] //不知道里面有什么:(


当前回答

下面是一些简单的解决方案。

它只对字符串显示"",对数字和函数/方法不显示""(如果方法是这样写的):

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod: function() {return "Hi there"}
  };
  
  let readableobj = '{ ';
  
  for(key in obj) {
    readableobj +=
    (typeof obj[key] === "string")? `${key}: "${obj[key]}", ` : `${key}: ${obj[key]}, `;
  }
 
  readableobj += '}';
  
  console.log('obj', readableobj); // obj { name: "Philips TV", price: 42, somemethod: function() {return "Hi there"}, }

这个解决方案使用尾随逗号(自ECMAScript 5起是合法的-请参阅MDN中的参考)。

代码基于'for in'循环的最简单形式:

let obj = {key: "value"};
for(key in obj) {
    return "The property " + key + " with value " + obj[key];
}

注意:它甚至适用于这种方法符号:

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod() {return "Hi there"}
  };

将结果显示为

    obj { name: "Philips TV", price: 42, somemethod: somemethod() {return "Hi there"}, } 

甚至对于箭头函数符号

  let obj = {
        name: "Philips TV",
        price: 2500,
        somemethod: () => {return "Hi there"}
  };

将结果显示为

    obj { name: "Philips TV", price: 42, somemethod: () => {return "Hi there"}, }

因此,你可以以一种可接受的格式显示一个对象,即使它里面有三种形式的方法符号,就像这样:

  let obj = {
        name: "Philips TV",
        price: 2500,
        method1: function() {return "Hi there"},
        method2() {return "Hi there"},
        method3: () => {return "Hi there"}
  };

有人可能会看到,即使是第二种格式method2() {return "Hi there"},通过复制它的标识符,最终也会显示为一个对键:值

// method2: method2() {return "Hi there"}

最后,true / false、undefined、null的处理方式与数字和函数相同(在最终格式中没有显示“”),因为它们也不是字符串。

重要的是:

JSON.stringify()销毁原始对象,这意味着方法丢失,并且不会显示在由它创建的最终字符串中。

因此,我们可能不应该接受涉及它的使用的解决方案。

console.log('obj', JSON.stringify(obj)); // obj {"name":"Philips TV","price":2500} // which is NOT acceptable

其他回答

如果你想要的只是一个字符串输出,那么这应该工作:

在你知道对象只是一个布尔值的情况下,日期,字符串,数字等…javascript的String()函数工作得很好。我最近发现这在处理来自jquery的$的值时很有用。每个函数。

例如,下面将“value”中的所有项转换为字符串:

$.each(this, function (name, value) {
  alert(String(value));
});

详情如下:

http://www.w3schools.com/jsref/jsref_string.asp

如果只是想查看用于调试的对象,可以使用

var o = {a:1, b:2} 
console.dir(o)

在检查最后一项时,使用reduce来更改(key,value)元组之间的分隔符sep的修改方法:

/**
     * Object to string
     * @param {*} obj 
     * @param {*} k_sep keys separator
     * @param {*} v_sep values separator
     * @returns 
     */
    var objectToString: function (obj, k_sep = '=', v_sep = ',') {
      const entries = Object.entries(obj);
      return entries.reduce((str, [p, val], counter) => {
        if (counter < entries.length - 1) {
          return `${str}${p}${k_sep}${val}${v_sep}`;
        } else {
          return `${str}${p}${k_sep}${val}`;
        }
      }, '');
    }

/** * Object to string * @param {*} obj * @param {*} k_sep keys separator * @param {*} v_sep values separator * @returns */ var objectToString = function(obj, k_sep = '=', v_sep = ',') { const entries = Object.entries(obj); return entries.reduce((str, [p, val], counter) => { if (counter < entries.length - 1) { return `${str}${p}${k_sep}${val}${v_sep}`; } else { return `${str}${p}${k_sep}${val}`; } }, ''); } console.log( objectToString({ status_code: 200, execute_time: 0.1, ip: '1270.0.0.1' }, ':', ",")) console.log( objectToString({ status_code: 200, execute_time: 0.1, ip: '1270.0.0.1' }, '=', ","))

如果你只关心字符串、对象和数组:

function objectToString (obj) {
        var str = '';
        var i=0;
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if(typeof obj[key] == 'object')
                {
                    if(obj[key] instanceof Array)
                    {
                        str+= key + ' : [ ';
                        for(var j=0;j<obj[key].length;j++)
                        {
                            if(typeof obj[key][j]=='object') {
                                str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
                            }
                            else
                            {
                                str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
                            }
                        }
                        str+= ']' + (i > 0 ? ',' : '')
                    }
                    else
                    {
                        str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
                    }
                }
                else {
                    str +=key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
                }
                i++;
            }
        }
        return str;
    }