0

I got a JSON result from PHP that looks like this below. I need to convert it into an array of objects like shown at the bottom.

How can I achieve this?

What I have

Milestones JSON

[
  {
    "id":0,
    "name":"None"
  },
  {
    "id":1,
    "name":"Milestone 1"
  },
  {
    "id":2,
    "name":"Milestone 2"
  },
  {
    "id":3,
    "name":"Milestone 3"
  },
  {
    "id":4,
    "name":"Milestone 4"
  }
]

What I need

Milestones Array Of OBjects

var taskMilestonesArray = [{
        id: 0,
        name: 'None',
    },
    {
        id: 1,
        name: 'Milestone 1',
    },
    {
        id: 2,
        name: 'Milestone 2',
    },
    {
        id: 3,
        name: 'Milestone 3',
    },
    {
        id: 4,
        name: 'Milestone 4',
}];

UPDATE

I just realized they are both in almost exact same format already. I just need to pass the array of objects into a library that expects it to be in that format and I don't think I can pass the JSON in.

JasonDavis
  • 48,204
  • 100
  • 318
  • 537

2 Answers2

2

If you have that JSON in a string (for the sake of the example, I will assume you have a variable named yourJsonString that holds your json), you can parse it:

var taskMilestonesArray = JSON.parse(yourJsonString);
taxicala
  • 21,408
  • 7
  • 37
  • 66
1

Use JSON.parse api to convert json string to the javascript object.

var taskMilestonesArray = JSON.parse('< milestones json string >');
rajuGT
  • 6,224
  • 2
  • 26
  • 44