Home > Back-end >  convert array to json in typescript
convert array to json in typescript

Time:11-06

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"}]

CodePudding user response:

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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related