如何将JavaScript对象转换为字符串?
例子:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
对象{a=1, b=2} //非常好的可读输出:) Item: [object object] //不知道里面有什么:(
如何将JavaScript对象转换为字符串?
例子:
var o = {a:1, b:2}
console.log(o)
console.log('Item: ' + o)
输出:
对象{a=1, b=2} //非常好的可读输出:) Item: [object object] //不知道里面有什么:(
当前回答
在检查最后一项时,使用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' }, '=', ","))
其他回答
这里没有一个解决方案对我有效。JSON。stringify似乎是很多人所说的,但它削减了函数,并且在我测试时尝试的一些对象和数组似乎很坏。
我做了自己的解决方案,至少在Chrome中工作。把它贴在这里,这样任何在谷歌上看到的人都能找到它。
//Make an object a string that evaluates to an equivalent object
// Note that eval() seems tricky and sometimes you have to do
// something like eval("a = " + yourString), then use the value
// of a.
//
// Also this leaves extra commas after everything, but JavaScript
// ignores them.
function convertToText(obj) {
//create an array that will later be joined into a string.
var string = [];
//is object
// Both arrays and objects seem to return "object"
// when typeof(obj) is applied to them. So instead
// I am checking to see if they have the property
// join, which normal objects don't have but
// arrays do.
if (typeof(obj) == "object" && (obj.join == undefined)) {
string.push("{");
for (prop in obj) {
string.push(prop, ": ", convertToText(obj[prop]), ",");
};
string.push("}");
//is array
} else if (typeof(obj) == "object" && !(obj.join == undefined)) {
string.push("[")
for(prop in obj) {
string.push(convertToText(obj[prop]), ",");
}
string.push("]")
//is function
} else if (typeof(obj) == "function") {
string.push(obj.toString())
//all other values can be done with JSON.stringify
} else {
string.push(JSON.stringify(obj))
}
return string.join("")
}
编辑:我知道这段代码可以改进,但只是从来没有做过。用户andrey在评论中提出了一个改进:
这里有一点变化的代码,它可以处理'null'和'undefined',也没有添加过多的逗号。
使用它在你自己的风险,因为我没有验证它在所有。请随意提出任何额外的改进意见。
请不要使用此答案,因为它只在某些版本的Firefox中有效。没有其他浏览器支持它。使用加里钱伯斯解决方案。
toSource()是您正在寻找的函数,它将以JSON的形式写入。
var object = {};
object.first = "test";
object.second = "test2";
alert(object.toSource());
我建议使用JSON。stringify,它将对象中的变量集转换为JSON字符串。
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
大多数现代浏览器都支持这种方法,但对于那些不支持的浏览器,您可以包含一个JS版本。
在console中保持简单,你可以使用逗号而不是+。+将尝试将对象转换为字符串,而逗号将在控制台中单独显示它。
例子:
var o = {a:1, b:2};
console.log(o);
console.log('Item: ' + o);
console.log('Item: ', o); // :)
输出:
Object { a=1, b=2} // useful
Item: [object Object] // not useful
Item: Object {a: 1, b: 2} // Best of both worlds! :)
参考:https://developer.mozilla.org/en-US/docs/Web/API/Console.log
var o = {a:1, b:2};
o.toString=function(){
return 'a='+this.a+', b='+this.b;
};
console.log(o);
console.log('Item: ' + o);
因为Javascript v1.0可以在任何地方工作(甚至是IE) 这是一种本地方法,允许在调试和生产过程中对对象进行定制 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
有用的例子
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
还有,作为奖励
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