0

In my Vue application I have a list of objects looking like this:

const arr = [
   {
     id: 1,
     name: 'Max',
     grade: 3
   },
   {
     id: 2,
     name: 'Lisa',
     grade: 2
   }
];

Now I want every object in this array to be a single string for itself. I know there is JSON.stringifty but this makes my whole array to a string and not every single object.

So the result should be something like:

const arr = [
"{id:1,name:'Max',grade:3}",
"{id:2,name:'Max',grade:3}"
];
Warm Red
  • 287
  • 2
  • 8

2 Answers2

4

That would be

const myJsonArr = arr.map((v) => JSON.stringify(v))
spender
  • 117,338
  • 33
  • 229
  • 351
  • `JSON` is a module, not an object, hence `arr.map(JSON.stringify)` would be fine – gog Nov 24 '22 at 10:04
  • 1
    @gog I wouldn't do that. map passes an integer index and the original array as the 2nd and 3rd arguments. stringify expects different things – Trevor Dixon Nov 24 '22 at 10:08
  • `If replacer is anything other than a function or an array... all properties of the object are included in the resulting JSON string. If space is anything other than a string or number... no white space is used.` - so we're fine. – gog Nov 24 '22 at 10:14
  • @gog Having to delve deep into the docs about exactly what parameters `map` uses to invoke its callback vs the parameters accepted by `JSON.stringify` just isn't worth the time. By wrapping, we can be very sure, at first glance, that `JSON.stringify` is being called correctly. – spender Nov 24 '22 at 13:04
0

you can try it

let array = arr.map(item=>JSON.stringify(item))
NAZIR HUSSAIN
  • 578
  • 1
  • 18