Retrieve data using the designated key and convert it into JSON format

If I have the following JSON array:

[
    {"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"}
        ]
    }
]

What is the best way to transform it into the format below?

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

Answer №1

If you want to tackle this task using pure JavaScript, the functional approach is definitely the way to go. It's sleeker, more elegant, and gets the job done faster. One technique you can employ is creating a key/value hashmap to manage your data effectively.

Two powerful methods that come in handy for this scenario are Array.prototype.reduce() and Array.prototype.concat().

// Combine reduce and concat to build an array
// Start by initializing the process with an empty object
var filter = [].concat.apply(array[0].data.reduce(function(hash, current) {
    // Check if the hashmap already has the current.W key
    return hash.hasOwnProperty(current.W) 
        // If yes, add the current object to the existing array under that key
        ? (hash[current.W].push({'A1': current.A1}), hash)
        // If not, create a new key-value pair with an array as the value
        : (hash[current.W] = [{'A1': current.A1}], hash);
}, {}));

console.log(filter);

Answer №2

If you're looking to group elements in a collection, consider using underscore:

GroupBy Function in Underscore.js

The groupBy function in Underscore.js allows you to split a collection into sets based on the result of applying an iteratee function to each element. You can provide either a function or a property name as the iteratee.

Example using _.groupBy:
_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}

Another example:
_.groupBy(['one', 'two', 'three'], 'length');
=> {3: ["one", "two"], 5: ["three"]}

Answer №3

To simplify the process, consider doing some reduction:

var obj = [{
        "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" }
        ]
    }],
    grouped = obj[0].data.reduce(function (r, a) {
        r[a.W] = r[a.W] || [];
        r[a.W].push({ A1: a.A1 });
        return r;
    }, {}),
    groupedAsDesired = Object.keys(grouped).reduce(function (r, a) {
        var o = {};
        o[a] = grouped[a];
        r.push(o);
        return r;
    }, []);

document.write('<pre>grouped: ' + JSON.stringify(grouped, 0, 4) + '</pre>');
document.write('<pre>groupedAsDesired: ' + JSON.stringify(groupedAsDesired, 0, 4) + '</pre>');

A helpful tip is to avoid wrapping objects with different properties in arrays for your desired result. Compare the results of grouped and groupedAsDesired in the output window.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Similar to LINQ's Enumerable.First(predicate) method but with a slightly different syntax, this

When working with JavaScript, we often encounter situations where we need to find the first matching element based on certain conditions. Take for example this code snippet: function process() { var firstMatch = ['a', 'b', 'c&ap ...

Issues with aligning center vertically and horizontally using flexbox are causing unexpected behavior

Understanding the basic concepts of centering a flex container using justify-content:center and align-items: center, I am facing an alignment issue with my box. Can anyone help me with this? This is what I have attempted so far: <template> <di ...

Replace the checkbox display heading with a text box in the designated area

I'm new to using kendo ui Currently, I am attempting to show a text box in the first column header. Instead of the checkboxDisplay heading, I want to replace it with a text box. Could someone please provide guidance on how to resolve this issue? Here ...

Securing NextJS API Routes with API Key Authorization

I'm developing an app in NextJS 13 that utilizes API routes, and I aim to secure them against any unauthorized access from external functions. While my app integrates Auth0, there is no strict requirement for protection since unregistered individuals ...

Wcf Service does not define Angular JS methods

I am utilizing a WCF Service within an AngularJS application. The WCF Service is functional, and I am attempting to display a list of user records from a SQL database. However, upon running the application, I encountered the following errors: angular.js: ...

Verifying JSON array compatibility in PostgreSQL database

I am facing a challenge with a JSONB array in my postgres database. It is structured as follows: { "id" : 22323, "details" : [ { "status" : "stage1", "timestamp" : "201 ...

What's the best way to invoke a function from a different JS file or create a custom event in JQuery that includes a parameter as a data object?

I am facing an issue while using requireJS to call a function from a required JS file. In my main app.js "controller", I have included (plugin)app.js, which contains all plugin configurations and related functions. The snippet below is from app.js defin ...

Altering the color of a div based on a specified value condition

I am in need of assistance with a div structure similar to this: <div id="namacoc" tabindex="1" class="filled-text" placeholder="Input your name" contenteditable ></div> <div id="position" tabindex="1" class="filled-text" placeholder="Input ...

Using a Typescript variable prior to its assignment

I encountered an issue in my Typescript / ReactJS project displaying the error message Variable 'myVar' is used before being assigned. TS2454 This problem arises with my TS version 4.2.3, appearing both in my IDE and during code execution. Inte ...

Guidelines on integrating Admob into Ionic framework

I tried following the steps outlined in this post: AdMob not loading ads in ionic/angular app After running the app using "ionic build ios && ionic emulate ios," I still see no ads, no black bar, nothing at all. Can someone help me figure out wha ...

Logging in using Selenium WebDriver in Java

I'm just starting out with selenium webdriver and I need to automate a webpage for my project. Right now, I'm working on the login page but I'm having trouble with the login button. I'm not sure which locator to use for it. The login bu ...

The error message "TypeError: addNewUser is not a function in React.js onSubmit

What could be causing the error message "TypeError: addNewUser is not a function"? The issue arises when I complete the form and click save, displaying the error that addNewUser is not defined as a function. The problem occurs within the following code ...

Attempting to retrieve an image from the database using ajax within a PHP script

I'm facing an issue with my code where I am attempting to retrieve an image from a database using AJAX, but it's not working as expected. Can someone please help me out? Image uploading works fine when trying to fetch the image using an anchor ta ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

I want to display events from my database table on their corresponding dates using JavaScript and jQuery. How can I achieve this?

Using the FullCalendar plugin, I attempted to achieve a specific functionality, but unfortunately fell short of my goal. Below is the snippet of my scripting code: $('#calendar').fullCalendar({ //theme: true, header: { ...

Executing a JavaScript function within MainPage.xaml.cs codebehind file in a Windows application

I am currently working on a project developing a Windows 8.1 app using HTML5 and Javascript (Silverlight). I have encountered an issue with implementing the functionality for the hardware back button. Within the MainPage.xaml.cs Codebehind file, I need to ...

What is the best way to make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

Guide to generating a map of a Java POJO class or JSON String with basic data types

I need to create a Map (String, Object) with the following format: {AssessmentId=0, Physical_name='ram', Physical_height=20, Physical_weight=60} This map will be constructed from my Pojo Class - InitialAssessment public class InitialAssessment ...

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...

Parsing JSON data into a Spark dataset that includes an inner array

While attempting to import JSON data into a dataset using Spark 2.1.1, I encountered an issue where it failed with the following error: Caused by: java.lang.NullPointerException: Null value appeared in non- nullable field: - field (class: "scala.Long", na ...