Read by key and parse as JSON in JavaScript

In JavaScript, you often need to group JSON data by specific keys and transform the structure. This tutorial shows how to read data by key values and reorganize it into a grouped JSON format.

Problem Statement

Given a JSON array with nested data, we want to group items by a specific key (like "W") and create a new structure where each group becomes a separate object.

Starting with this data structure:

const arr = [{
    "data": [
        { "W": 1, "A1": "123" },
        { "W": 1, "A1": "456" },
        { "W": 2, "A1": "4578" },
        { "W": 2, "A1": "2423" },
        { "W": 2, "A1": "2432" },
        { "W": 2, "A1": "24324" }
    ]
}];

Expected Output

We want to transform it into this grouped structure:

[
    {
        "1": [
            { "A1": "123" },
            { "A1": "456" }
        ]
    },
    {
        "2": [
            { "A1": "4578" },
            { "A1": "2423" },
            { "A1": "2432" },
            { "A1": "24324" }
        ]
    }
]

Solution Using reduce()

The solution uses the reduce() method twice: first to group by key, then to format the output:

const arr = [{
    "data": [
        { "W": 1, "A1": "123" },
        { "W": 1, "A1": "456" },
        { "W": 2, "A1": "4578" },
        { "W": 2, "A1": "2423" },
        { "W": 2, "A1": "2432" },
        { "W": 2, "A1": "24324" }
    ]
}];

const groupJSON = (arr = []) => {
    // Step 1: Group by W key
    const preCombined = arr[0].data.reduce((acc, val) => {
        acc[val.W] = acc[val.W] || [];
        acc[val.W].push({ A1: val.A1 });
        return acc;
    }, {});
    
    // Step 2: Convert to array of objects
    const combined = Object.keys(preCombined).reduce((acc, val) => {
        const temp = {};
        temp[val] = preCombined[val];
        acc.push(temp);
        return acc;
    }, []);
    
    return combined;
};

console.log(JSON.stringify(groupJSON(arr), undefined, 4));
[
    {
        "1": [
            {
                "A1": "123"
            },
            {
                "A1": "456"
            }
        ]
    },
    {
        "2": [
            {
                "A1": "4578"
            },
            {
                "A1": "2423"
            },
            {
                "A1": "2432"
            },
            {
                "A1": "24324"
            }
        ]
    }
]

How It Works

The function works in two main steps:

  1. Group by key: The first reduce() creates an object where each key corresponds to a "W" value, containing arrays of grouped items.
  2. Format output: The second reduce() converts the grouped object into an array of separate objects, each containing one group.

Alternative Approach Using Map

You can also use a Map for cleaner grouping logic:

const groupJSONWithMap = (arr = []) => {
    const groups = new Map();
    
    // Group items by W value
    arr[0].data.forEach(item => {
        if (!groups.has(item.W)) {
            groups.set(item.W, []);
        }
        groups.get(item.W).push({ A1: item.A1 });
    });
    
    // Convert Map to array of objects
    return Array.from(groups.entries()).map(([key, value]) => ({
        [key]: value
    }));
};

console.log(JSON.stringify(groupJSONWithMap(arr), undefined, 4));

Conclusion

This technique demonstrates how to read JSON data by specific keys and restructure it using reduce() or Map. The approach is useful for data transformation and API response formatting tasks.

Updated on: 2026-03-15T23:19:00+05:30

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements