-1

Does anyone know what is the best way to reformat JSON code below using only es5 ?I haven`t done much json formatting, thats why open for suggestions.

{
  "success": true,
  "results": [
    {
      "id": "12",
      "base": "263422"
 },
    {
      "id": "15",
      "base": "223322"
 }
}

to:

{
    "success": true,
    "results": [
        {
            "id": 29,
            "bill": [
                {
                    "id": 29,
                    "base": 124122,
                }
            ]
        },
        {
            "id": 33,
            "bill": [
                {
                    "id": 33,
                    "base": 12412232
                }
            ]
        }
    }
Anton
  • 1,344
  • 3
  • 15
  • 32
  • 3
    I can't see the connection between the first snippet and the excited result. Where does `bill` come from? Why are the `id` properties different (and repeated)? – David Thomas Jan 05 '19 at 00:22

1 Answers1

0

Something akin to this should work (provided you are simply looking to reformat the structure and not the data itself):

var json = {
    "success": true,
    "results": [
        {
            "id": "12",
            "base": "263422"
        },
        {
            "id": "15",
            "base": "223322"
        }
    ]
};

for(var i = 0; i < json.results.length; i++) {
    json.results[i].bill = [
        {
            id: json.results[i].id,
            base: json.results[i].base
        }
    ];

    delete json.results[i].base;
}

console.log(JSON.stringify(json, null, 4));
Ben
  • 2,441
  • 1
  • 12
  • 16