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

Ways to verify every entered word without having to click a button

My goal is to implement real-time word checking in a textarea using JavaScript/Angular. I want to validate each word as users are typing it out. What is the best approach for achieving this? ...

Create a line chart with multiple lines using data retrieved from either JSON or MySQL

At the outset, I must confess that I am not a programmer, although I am slowly getting the hang of it. My interest lies in utilizing graphs for Horticultural purposes. Currently, I have a database that receives data from sensors hourly, and my query retrie ...

Unable to retrieve the properties of a JavaScript object

Currently I am working on a React webApp project and encountering difficulties when trying to access data within a JavaScript Object. Below is the code snippet in question: const user_position = System.prototype.getUserPosition(); console.log({user ...

The error message "window is not defined" is commonly encountered in Next

Having some trouble with using apexcharts in a next.js application, as it's giving me an error saying 'window is not defined'. If anyone has any insights or solutions, I would greatly appreciate the help. Any ideas on what could be causing ...

Google Calendar Data in JSON Format

After establishing a public calendar on Google, I aimed to utilize its JSON file for embedding it onto my website. The link to view the calendar is available here. I am encountering difficulties in executing it, and what strikes me is that renowned JSON f ...

Updating an array using `setState` does not result in the array being updated

I created a component that uses the .map() method to render an array of students and has a button to shuffle and update the display. However, I'm facing an issue where the display does not update every time I click the button. const Home: NextPage = ...

Cleaning user Input in Rails 4

I've been developing an API using Ruby on Rails and I'm curious to know if there are any built-in methods or libraries/gems in Rails that help with sanitizing JSON and SQL data. Does Rails 4 handle this automatically? Specifically, I'm conce ...

Showing every piece of information line by line while uploading an AJAX CSV file

I have successfully parsed a CSV file using Papaparse, Jquery AJAX, and PHP. Now, I want to display the data line by line while the CSV file is being uploaded. Here is a snippet of my code: var xhr_file = null; $('#fileVariants').change(functio ...

Troubleshooting issues with sending POST requests in node.js

I've been attempting to initiate a post request, but for some reason, it's not going through. Strangely, I'm not seeing any output in the console log of my browser. My node server.js is up and running on x.x.x.x:8000. I've connected it ...

Performing XMLHttpRequests and ajax requests inside a foreach loop

I am facing a issue with echoing the decoded array using var_dump. Each time I click the button, a unique xmlhttprequest and ajax call should get executed for every row. However, in reality, the ajax doesn't work as expected. Upon examining the source ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

What are the steps for creating a dropdown menu that allows for easy selection of the correct item

I am dealing with a dropdown menu as shown below. <select name="slt"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="3">Three +</option&g ...

Chip input component in React

I've recently upgraded to React 17 and encountered an issue with chip input fields like material-ui-chip-input not working properly. I've tried various npm packages, but none of them seem to be compatible with React version 17. Does anyone know ...

Tips for avoiding cursor sticking in css rotate transform in firefox?

I have a unique challenge in this code where I want the user to grab the black square and rotate it around the inner circle. Check out the code snippet here. While attempting to rotate the square, you might notice that the cursor sometimes gets stuck in ...

how to transfer data from backend servlet to frontend javascript

Hey, I'm still learning about servlets so please excuse any confusion in my message! So basically, I'm trying to figure out how to pass a value from a servlet to JavaScript or even retrieve values from a servlet method within JavaScript. But I&ap ...

Utilizing a PHP Class object in Javascript by accessing its properties within a Javascript function

I'm struggling to access the attributes of an object within a JavaScript function that I created. This object was originally a PHP object that I converted to JSON using json_encode() In my project, there is 1 PHP file and 1 external JS file. In the ...

What is the best way to implement debouncing for an editor value that is controlled by the parent component?

Custom Editor Component import Editor from '@monaco-editor/react'; import { useDebounce } from './useDebounce'; import { useEffect, useState } from 'react'; type Props = { code: string; onChange: (code: string) => void ...

Is there a way to prevent the jsonPayload in stackdriver from automatically converting to a struct format?

When working with a Google Cloud Function, I am logging a simple JSON structure like this: console.info(JSON.stringify({message: 'xxx', data: {status: 200}, status: 200})); However, the log appears in an unreadable format in Stackdriver. How ca ...

Transforming JSON-like structure into JSON format

Recently, I came across a filtered JSON file that lost its original structure. The content of the file is presented in a way that each line looks like this: {u'spec1': {u'property1': u'12345', u'property2': ...

Encountering a DataCorrupted error while decoding a JSON file

Attempting to work with JSON for the first time, I may be making a beginner's mistake. My goal is simple - I want to populate an array of a class with data from a JSON file. Below is the code I have been working on: AN EXTENSION IN BUNDLE TO DECODE ...