Search code examples
javascriptjsontypescript-types

Generate custom Json from an object Array


I'm trying to generate a json from an array of objects using the JSON.stringify() funtion. The structure of the array is the following one:

export interface FilledCells {
  floor?: number;
  coordinates: {
    x: number;
    y: number;
  };
  type: string | undefined;
  seat: number;
  bikeSize?: string;
  group: string;
} 

Using the JSON.stringify(array) function will produce this result:

[
 {
  "floor": 0,
  "coordinates": {
   "x": 23,
   "y": 1
  },
  "type": "regular",
  "seat": 2,
  "group": "A"
 },
 {
  "floor": 0,
  "coordinates": {
   "x": 24,
   "y": 1
  },
  "type": "premium",
  "seat": 1,
  "group": "A"
 }
]

Now my question is, how can I customuize this json structure before sending it to the back end? I need to add a field at the begginning called "layout" and also each object should be contained in an array called "seats". What I'm trying to obtain is something like this:

"seatingConfiguration": [
            {
                "layout": "regular",
                "seats": [
                {
                    "floor": 0,
                    "coordinates": {
                         "x": 23,
                         "y": 1
                     },
                    "type": "regular",
                    "seat": 2,
                    "group": "A"
                },
                {
                    "floor": 0,
                    "coordinates": {
                         "x": 24,
                         "y": 1
                     },
                    "type": "premium",
                    "seat": 1,
                    "group": "A"
                }
                ]
            },
        ]

Thank you :)


Solution

  • Is this what you need?

    const array = [
        {
            floor: 0,
            coordinates: {
                x: 23,
                y: 1
            },
            type: "regular",
            seat: 2,
            group: "A"
        },
        {
            floor: 0,
            coordinates: {
                x: 24,
                y: 1
            },
            type: "premium",
            seat: 1,
            group: "A"
        }
    ]
    
    const jsonstring = JSON.stringify({
        seatingConfiguration: [
            {
                layout: "regular",
                seats: array
            }
        ]
    })
    
    console.log(jsonstring)
    
    console.log(JSON.parse(jsonstring))