Open In App

Formatting Dynamic JSON array JavaScript

Formatting a Dynamic JSON array is important because it organizes complex data structures, making them easier to read, manipulate, and communicate within applications and APIs. We will explore approaches to formatting dynamic JSON arrays in JavaScript.

Below are the approaches to format dynamic JSON arrays in JavaScript:

Using for...in Loop

In this approach, we are using a for...in loop to iterate over the elements in the jsonData array of objects. During each iteration, we extract the properties name, role, and experience from each object and push them into the res.temp array, resulting in a formatted JSON structure for the data.

Example: The below example uses for...in Loop to format dynamic JSON array in JavaScript.

let jsonData = [{
    name: "Gaurav",
    role: "Developer",
    experience: 5
},
{
    name: "Saurav",
    role: "Designer",
    experience: 3
},
{
    name: "Ravi",
    role: "Manager",
    experience: 8
},
];
let res = {
    temp: []
};
for (let i in jsonData) {
    let item = jsonData[i];
    res.temp.push({
        "name": item.name,
        "role": item.role,
        "experience": item.experience
    });
}
console.log(JSON.stringify(res, null, 2));

Output
{
  "temp": [
    {
      "name": "Gaurav",
      "role": "Developer",
      "experience": 5
    },
    {
      "name": "Saurav",
      "role": "Designer",
      "experience": 3
    },
    {
      "na...

Using Array.map()

In this approach, we are using Array.map() to iterate over the elements in the jsonData array of objects. For each item in the array, we extract the properties name, role, and experience, and push them into the res.gfg array, resulting in a formatted JSON structure for the data.

Example: The below example uses Array.prototype.map() to format dynamic JSON array in JavaScript.

let jsonData = [{
    name: "Gaurav",
    role: "Developer",
    experience: 5
},
{
    name: "Saurav",
    role: "Designer",
    experience: 3
},
{
    name: "Ravi",
    role: "Manager",
    experience: 8
},
];

let res = {
    gfg: []
};
jsonData.map(function (item) {
    res.gfg.push({
        "name": item.name,
        "role": item.role,
        "experience": item.experience
    });
});
console.log(JSON.stringify(res, null, 2));

Output
{
  "gfg": [
    {
      "name": "Gaurav",
      "role": "Developer",
      "experience": 5
    },
    {
      "name": "Saurav",
      "role": "Designer",
      "experience": 3
    },
    {
      "nam...
Article Tags :