bafix2203
bafix2203

Reputation: 541

Different delimiters in javascript toString()

I have :

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

And it returns the output like this zero,1,two,2,three,3.

I want

zero:1,two:2,three:3

Thanks for answers in advance!

Upvotes: 0

Views: 48

Answers (2)

GansPotter
GansPotter

Reputation: 781

you can try this

if key or value doesn't include '{','}','[',']' in it

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

Else you can try this,

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 )

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386883

You need to iterate the object's entries and join them.

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

Upvotes: 4

Related Questions