-1

Dears, this is my array:

(3) [{…}, {…}, {…}]
0
: 
{x: 2019, y: '0.50', label: 2019}
1
: 
{x: 2020, y: '0.00', label: 2020}
2
: 
{x: 2021, y: '3.80', label: 2021}
x
: 
0
length
: 
3
[[Prototype]]
: 
Array(0)

I need it in [{ x: 2019, y: 0.50, label: "2019" }, { x: 2020, y: 0.00, label: "2020" }, { x: 2021, y: 3.80, label: "2021" },]; format.

Please help me to do this.

CSDev
  • 3,177
  • 6
  • 19
  • 37
  • 4
    its already in the format you need? – cmgchess Dec 19 '22 at 06:47
  • 1
    Could you please explain what is the current format of your data? Because from your message I get that you want an array of objects converted into an array of objects... – Emilien Dec 19 '22 at 06:47
  • The only difference I see is `y` is converted from a string to a number while `label` is changed other way round. But, since this is for a chart, I don't think that's gonna matter much. – adiga Dec 19 '22 at 07:02
  • I suspect the "I have this" sample is copied from a browser console log, and is just how the log is displaying the data (which, apart from some string-to-number conversions, is the same data as in your "I need it in" sample.) – Daniel Beck Dec 20 '22 at 19:21

1 Answers1

-1

You can use the JSON.stringify(arrayName) method.

Example:

(3) [{…}, {…}, {…}]
0: {
  x: 2019,
  y: '0.50',
  label: 2019
}
1: {
  x: 2020,
  y: '0.00',
  label: 2020
}
2: {
  x: 2021,
  y: '3.80',
  label: 2021
}
length: 3
[[Prototype]]: Array(0)

After using JSON.stringify(a)output is:

'[{"x":2019,"y":"0.50","label":2019},{"x":2020,"y":"0.00","label":2020},{"x":2021,"y":"3.80","label":2021}]'
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • While passing data to canvasjs dataPoints data is going like "[{ x: 2019, y: 0.50, label: "2019" }, { x: 2020, y: 0.00, label: "2020" }, { x: 2021, y: 3.80, label: "2021" },]" format. I need that without double quotes. How to do this. – Edwin K Biju Dec 19 '22 at 06:57
  • yes, we don't have any property to stringify without quotes. The solution can be to replace "" after using JSON.stringify https://stackoverflow.com/questions/11233498/json-stringify-without-quotes-on-properties – Mishika Dhar Dec 19 '22 at 09:54
  • This would convert the object into a JSON string, which is not at all what they were asking for. – Daniel Beck Dec 20 '22 at 19:19