Instructions for transforming rows into columns in JSON format

Looking to convert an array of JSON objects into a format where rows become columns and the values at the side become column values, similar to the crosstab function in PostgreSQL.

The JSON data looks something like this:

{"marketcode":"01","size":"8,5","amount":1},
{"marketcode":"01","size":"9","amount":1},
{"marketcode":"01","size":"10","amount":0},

I need it to be transformed into this structure:

{"marketcode": "01", "8,5": 1, "9": 1, "10": 0}

I've tried searching for a solution using Lodash, but haven't had any success so far.

Answer №1

Here is a potential solution that may meet your requirements:

const transformData = data => {
    const convertedData = data.reduce((result, {id, type, value}) => {
        if (result.has(id)) {
            result.set(id, {...result.get(id), [type]: value});
        } else {
            result.set(id, {id, [type]: value});
        }
        return result;
    }, new Map());
    return [...convertedData.values()];
};

fiddle: https://jsfiddle.net/exampleuser123/abcdefg123/

Answer №2

Hey Bill, I appreciate your help with my question. I initially thought there might be a library for this issue, but ended up coding a solution myself. Thank you so much for your assistance! Here is the code snippet:

companies.forEach((company, index) => {
 // place company in the code
 result[index] = {'company': company};
 // add numbering as columns and quantity in stock as well as sales number if applicable
 a.forEach(item => {
  // check if the numbering corresponds to the company
   if (result[index].company == item.company) {
    if (item.quantity !== undefined && item.sales !== undefined) {
     result[index][item.size] = item.quantity + '/' + item.sales;
    } else {
     result[index][item.size] = item.quantity + '/' + "0";
   }        
  }         
 });
});

fiddle: https://jsfiddle.net/v1hLs5o0/6/

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

JavaScript counter to monitor the number of requests made to the Open Weather Map API

Currently, I am utilizing the Open Weather Map's free API which allows me to make 1000 API calls per day through their One Call API. However, there is no built-in feature for tracking these calls in the Open Weather Map platform. To address this issue ...

How can I get electron to interact with sqlite3 databases?

I've exhausted all my options and still can't get it to function. This error message keeps popping up: https://i.stack.imgur.com/D5Oyn.png { "name": "test", "version": "1.0.0", "description": "test", "main": "main.js", "scripts": { ...

Obtain a URL using JavaScript's regular expressions

Is it possible to use JavaScript regex to fetch the first function parameter? For instance, when I click on a tag in this page element, how can I extract the inline link? Here's an example: <li><a href="#blog" data-rel="clos ...

Charting data with missing values in Google Charts

I have generated a line chart using php and json to load the data. The issue I am facing is that the chart displays NULL values as 0, which does not look good. My assumption is that I may be formatting the json incorrectly, and what I really need is {"v" ...

Using HTML5 input type number along with a regular expression pattern

In order to display only numbers and forward slashes in the input field with regex pattern, I attempted the following code: <input type="number" pattern="[0-9\/]*"> However, this code only shows the number pad from 0 to 9. How can I modify the ...

Display an HTML tag with JavaScript

My code is in both HTML and TS files. The content stored in the Description variable looks like this: <div>aaaa</div><div>bbbb</div><div>cccc</div> Currently, the output displays as follows: aaaabbbbcccc I want to modi ...

How to Unravel a JSON Document Using Pandas

I've been attempting to convert a JSON file into a pandas DataFrame. Despite trying various solutions like pd.json_normalize(data.json), none have proven successful. It seems that the file is more intricate and contains nested JSON data. How can I fl ...

What is the best way to duplicate a text using a button in ReactJS?

Hey there, I'm working with an array and trying to figure out how to copy the text in a p element ({item.adress} => this is part of an array item) when a button is clicked. Could you lend me a hand? import classes from './CryptoBox.module.css& ...

What are the two terms enclosed in brackets when using Matlab?

For what purpose is this syntax used? [sbox idx] = sort(box); Upon reviewing the information on Sorting array elements, I was anticipating to see something similar to: [sbox, idx] = sort(box); However, this is not the case based on the code provided (i ...

Issues with functionality arise when cloning HTML divs using JQuery

VIDEO I created a feature where clicking a button allows users to duplicate a note div. However, the copied note does not function like the original - it's not draggable and changing the color of the copied note affects the original note's color. ...

Utilizing AJAX for remote execution of JavaScript code

Suppose there is a JavaScript page located at myaddress/service.js on a server. The code in this .js file looks something like: nsBob = { a: function(someParam) {...perform actions and return result}, b: function() {...perform actions and return result} ...

Dynamic population of dropdown not working as expected

Below is the code I am using to populate a Dropdown: $(document).ready(function(){ $('#inDistrict').sSelect(); $("#inDistrict").change(function(){ $.getJSON("filldistricts.php",{id: $(this).val(), ajax: 'true'}, function(j) ...

Modify the button's border color upon click action

I am looking to implement a feature where the border of a button changes when clicked once and reverts back when clicked again. This should apply individually to each of the 16 buttons with the same class. Additionally, I want to enable the ability to clic ...

Converting 2D pixel art into 3D coordinates with ThreeJS

Attempting to display a cube generated in ThreeJS on an HTML canvas at a specific location has been quite challenging. The location is defined in pixels, for example (100,200). Unfortunately, the process of converting these pixel values into ThreeJS coord ...

Trouble with Displaying MKAnnotations on Map in iOS 9 with Swift 2.0

Attempting to showcase 100 EV charger stations on a map using annotations that display their name and address, but only one annotation is displaying correctly out of the 100 specified in the code below. The code compiles without any error flags, however, ...

Deleting elements from an array of objects in Angular Would you like help with

I have a JSON structure and I need to remove the entire StartGeotag object from the array. [{ CreatedDate: "2022-02-17T10:30:07.0442288Z" DeletedDate: null ProjectId: "05b76d03-8c4b-47f4-7c20-08d9e2990812" StartGeotag: { ...

React and the Use of External Libraries

Currently, I am developing a website with react and I am in need of installing mojs, mojs-timeline, and mojs-curve-editor. Unfortunately, these are not available as npm packages. Can anyone suggest the most effective method to integrate them into my react ...

PHP is unable to make updates to the record

I have been working on a function to update the "status" attribute in the "users" table. When the status is set to 1, it indicates that the user is online, while a status of 0 means that the user is offline. While coding a PHP file to automatically set th ...

Transforming JSON data into an interactive table with HTML

After spending four days searching for a solution, I am still unable to figure out my problem. My goal is to convert a JSON string data retrieved from a URL into a dynamic table using JQuery and JavaScript. To achieve this, I need to load the JSON string ...

Using jQuery to modify the CSS of a div located outside of an iframe

Currently, I am developing a straightforward script. Firstly, here is all of the code that I have: <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script type="text/javascript"> function SuperWebF1() { $("#outerd ...