Converting JavaScript Array to JSON object

I am trying to write a for or JQuery. Each loop so that It will generate a new JSON Object from an array in a desired format. I want to output a JSON Object from an input JavaScript Array. I have a following input array to convert:

INPUT:

    [
      {
        "parent": "parent_1",
        "child": "abc",
        "data": "data1"
      },
      {
        "parent": "parent_1",
        "child": "def",
        "data": "data2"
      },
      {
        "parent": "parent_1",
        "child": "ghi",
        "data": "data3"
      },
      {
        "parent": "parent_2",
        "child": "jkl",
        "data": "data4"
      },
      {
        "parent": "parent_2",
        "child": "acc",
        "data": "data5"
      },
      {
        "parent": "parent_3",
        "child": "mjh",
        "data": "data6"
      },
      {
        "parent": "parent_3",
        "child": "fg1",
        "data": "data7"
      },
      {
        "parent": "parent_2",
        "child": "dfg",
        "data": "data8"
      },
      {
        "parent": "parent_3",
        "child": "jkk",
        "data": "data9"
      },
      {
        "parent": "parent_4",
        "child": "3ff",
        "data": "data10"
      },
      {
        "parent": "parent_3",
        "child": "mhg",
        "data": "data11"
      },
      {
        "parent": "parent_1",
        "child": "gnh",
        "data": "data12"
      }
    ]

so from above array want to run a for or JQuery. Each loop so that it will generate a new JSON Object in the following format:

OUTPUT:

[
  {
    "parent_1": {
      "child": [
        {
          "name": "abc",
          "data": "data1"
        },
        {
          "name": "def",
          "data": "data2"
        },
        {
          "name": "gh1",
          "data": "data3"
        },
        {
          "name": "gnh",
          "data": "data12"
        }
      ]
    }
  },
  {
    "parent_2": {
      "child": [
        {
          "name": "jkl",
          "data": "data4"
        },
        {
          "name": "acc",
          "data": "data5"
        },
        {
          "name": "dfg",
          "data": "data8"
        }
      ]
    }
  },
  {
    "parent_3": {
      "child": [
        {
          "name": "mjh",
          "data": "data6"
        },
        {
          "name": "fg1",
          "data": "data7"
        },
        {
          "name": "jkk",
          "data": "data9"
        },
        {
          "name": "mhg",
          "data": "data11"
        }
      ]
    }
  },
  {
    "parent_4": {
      "child": [
        {
          "name": "3ff",
          "data": "data10"
        }
      ]
    }
  }
]

96 thoughts on “Converting JavaScript Array to JSON object”

Leave a Comment