0

i m trying to convert an array to json in typeScript, how can i do it to get this result please:

 let array=['element1', 'element2', 'element3']

result=[{"value"="element1"},{"value"="element2"}, {"value"="element3"}]
OuiSa
  • 3
  • 3
  • 1
    The result you want is invalid, both as JSON and as JavaScript. – Heretic Monkey Nov 05 '21 at 14:06
  • You appear to be confused about the difference between JSON, which is a text format for sending and storing data, and objects, which are simply another structure in JavaScript. See [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/q/2904131/215552). – Heretic Monkey Nov 05 '21 at 14:09

1 Answers1

0

To be clear, the JSON version of your array would be exactly that:

['element1', 'element2', 'element3']

If you want to add the value field, you can manually add it first, before converting into JSON.

Working demo

The below code produces this:

[{"value":"element1"},{"value":"element2"},{"value":"element3"}]

let array = ['element1', 'element2', 'element3']

let arrayWithValue = array.map(el => ({value: el}));

console.log(JSON.stringify(arrayWithValue));
Balastrong
  • 4,336
  • 2
  • 12
  • 31