-3

How do I take a javascript array

var array = [1,2,3,4,5,6]

And convert it to a JSON object that looks like this

[
  {
    "value": 1
  },
  {
    "value": 2
  },
  {
    "value": 3
  },
  {
    "value": 4
  },
  {
    "value": 5
  },
  {
    "value": 6
  }
]

The closest I've come is using this

JSON.stringify(Object.assign({}, array)); 

But it gives me an output like this

{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6}
Bazilby
  • 79
  • 1
  • 8
  • 3
    `array.map(value => ({ value }))` – Patrick Roberts Oct 08 '19 at 20:00
  • Thanks @adiga when I was searching for a solution the results you posted didn't show up. Maybe I'll just consult you in the future. – Bazilby Oct 08 '19 at 20:06
  • @Bazilby Or you could consult the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_methods) and guides such as [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/a/40195701/4642212). – Sebastian Simon Oct 08 '19 at 20:20
  • [There’s no such thing as a “JSON Object”](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). – Sebastian Simon Oct 08 '19 at 20:21

1 Answers1

1

You could map the values by taking a short hand property.

var array = [1, 2, 3, 4, 5, 6],
    result = array.map(value => ({ value }));

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392