如何将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] //不知道里面有什么:(
当前回答
对于非嵌套对象:
Object.entries(o).map(x=>x.join(":")).join("\r\n")
其他回答
如果你可以使用lodash,你可以这样做:
> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'
使用lodash map()也可以遍历对象。 这将每个键/值条目映射到它的字符串表示形式:
> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]
join()将数组条目放在一起。
如果你可以使用ES6模板字符串,这也是有效的:
> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'
请注意,这不是递归通过对象:
> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]
就像node的util.inspect()一样:
> util.inspect(o)
'{ a: 1, b: { c: 2 } }'
这里没有一个解决方案对我有效。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',也没有添加过多的逗号。
使用它在你自己的风险,因为我没有验证它在所有。请随意提出任何额外的改进意见。
function objToString (obj) {
var str = '{';
if(typeof obj=='object')
{
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + ':' + objToString (obj[p]) + ',';
}
}
}
else
{
if(typeof obj=='string')
{
return '"'+obj+'"';
}
else
{
return obj+'';
}
}
return str.substring(0,str.length-1)+"}";
}
我希望这个例子将有助于所有那些谁都在数组对象的工作
var data_array = [{
"id": "0",
"store": "ABC"
},{
"id":"1",
"store":"XYZ"
}];
console.log(String(data_array[1]["id"]+data_array[1]["store"]));
如果只是想查看用于调试的对象,可以使用
var o = {a:1, b:2}
console.dir(o)