JavaScript toString()中的不同定界符

时间:2018-07-25 09:42:58

标签: javascript tostring

我有:

var myArray = [{
  'zero': '1'
}, {
  'two': '2'
}, {
  'three': '3'
}];
var result = myArray.toString();
console.log(result);

它返回像这样的输出zero,1,two,2,three,3.

我想要

zero:1,two:2,three:3

感谢提前答复!

2 个答案:

答案 0 :(得分:4)

您需要迭代对象的条目并将其加入。

var array = [ {'zero':'1'}, {'two':'2'}, {'three':'3'}],
    result = array.map(o => Object.entries(o).map(a => a.join(':'))).toString();
    
console.log(result);

答案 1 :(得分:2)

您可以尝试

如果键或值中不包含'{','}','[',']'

var myArray = [ {'zero':'1'}, {'two':'2'}, {'three':'3'}];
var result = JSON.stringify( myArray )
result = result.replace(/[{\[\]}]/g,'').replace(/["']/g, "")
console.log( result )

否则,您可以尝试一下

var myArray = [ {'ze{ro':'1'}, {'two':'2'},{'thre]e':'3'}];

var result = ''
myArray.forEach( data => {
Object.keys( data ).forEach( key => {
  result = result + key + ':' + data[ key ] + ','
})
})
result = result.substring( 0 , result.length - 1 )
console.log( result )