-4

I need to make this array into one string - quotation marks around the whole thing - not affecting the individual elements - therefore JSON.stringify doesnt work.

[ { name: 'red', id: '1' },
  { name: 'yellow', id: '2' },
  { name: 'black', id: '3' },
  { name: 'white', id: '4' } ]

needs to be

"[ { name: 'red', id: '1' },
 { name: 'yellow', id: '2' },
 { name: 'black', id: '3' },
 { name: 'white', id: '4' } ]"

I do not want to make every element of the array a string, I just want to put quotation marks around the whole thing. I've tried doing arr.join() and i just get '[object Object],[object Object],[object Object],[object Object]' Is there a simple way of doing this?

E.Moon
  • 5
  • 5

2 Answers2

0

You can use JSON.stringify

var x=[ { name: 'red', id: '1' },
  { name: 'yellow', id: '2' },
  { name: 'black', id: '3' },
  { name: 'white', id: '4' } ];
  
  var y=JSON.stringify(x);
  alert(y)
sumeet kumar
  • 2,628
  • 1
  • 16
  • 24
0

let arr = [
  { name: 'red', id: '1' },
  { name: 'yellow', id: '2' },
  { name: 'black', id: '3' },
  { name: 'white', id: '4' }
];
  
let string = JSON.stringify( arr );

console.log( typeof string );

enter image description here

  • this puts every element in quotation marks, and not the whole thing... which is the opposite of what i want to do – E.Moon Oct 26 '17 at 07:57
  • No. It works absolutely right. See attached picture. The checking of type in code snippet proves it. – ivan.posokhin Oct 26 '17 at 10:48