Using Vue.js to group JSON arrays multiple times

I have a program that I utilize to import a CSV data file and then convert it into JSON format.

The resulting JSON structure is as follows:

{
  "Class": "Cultivated Mushrooms",
  "Type": "Shii-take",
  "Grade": "Medium",
  "LvH": "SP",
  "Description": "SHIITAKE MEDIM STEMLESS unclosed",
  "Trade unit composition": "8 x 150gr",
  "Punnet type": "CARTON",
  "CONTAINER BOX": "Multicrate (30x40x11)",
  "Price (/box)": "10",
  "Amount (container box) per Pallet / Europallet \r": "200 / 160\r"
}

Output in the console log:

https://i.sstatic.net/X3Gg4.png

I need to group the data by Category > Type > Grade, but I am unsure how to achieve this using VUE/JS.


I can successfully group the data by individual fields like so

In the methods section:

groupBy: function (array, key){
  const result = {};
   array.forEach(item => {
    if (!result[item[key]]){
      result[item[key]] = []
    }
    result[item[key]].push(item)
   });
  return result
},

Computed property:

groups() {
  return this.groupBy(this.parse_csv, 'Class');
},

This grouping operation is quite straightforward in SQL, demonstrated here on DBFiddle (the example includes all the JSON data).

The desired outcome should resemble https://i.sstatic.net/1cn3U.png

Despite thorough research and attempts, I came across this informative response. However, I am struggling to adapt this solution into VUE due to my limited knowledge of JavaScript. Any additional insight would be greatly appreciated.

Answer №1

When working with multiple keys instead of a single key, you can obtain an array of keys. Then, create a unique key by combining the values corresponding to each of those keys with a | separator.

groupBy: function(array, keys){
  const result = {};
   array.forEach(item => {
    // get an array of values and join them with | separator
    const key = keys.map(k => item[k]).join('|');
    // use that unique key in result
    if (!result[key]){
      result[key] = []
    }
    result[key].push(item)
   });
  return result
}

For the object provided, the unique key would be as follows:

Gecultiveerde paddestoelen|Shii-take|Medium

Here is a snippet showcasing this logic:

function groupBy (array, keys){
  const result = {};
   array.forEach(item => {
    const key = keys.map(k => item[k]).join('|');
    if (!result[key]){
      result[key] = []
    }
    result[key].push(item)
   });
  return result
}

const input=[{Class:"Gecultiveerde paddestoelen",Soort:"Shii-take",Sortering:"Medium",LvH:"SP",Omschrijving:"SHIITAKE MEDIM STEMLESS unclosed","Trade unit composition":"8 x 150gr","Punnet type":"CARTON","CONTAINER BOX":"Multicrate (30x40x11)","Price (/box)":"10","Amount (container box) per Pallet / Europallet \r":"200 / 160\r"}];

console.log(groupBy(input, ['Class', 'Soort', 'Sortering']))

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

A method in JavaScript to fetch a single variable using the GET request

Although I am new to writing JavaScript, I am currently working on an iOS application that will make use of JavaScriptCore's framework to interpret a piece of javascript code in order to obtain a specific variable. My goal is to establish a GET reques ...

Building Unique Staircases with Three.js Geometry

I have been working on creating a custom three.js geometry for round staircases, but I seem to have made some errors with the vertices and indexes of the steps. Below is an example staircase that utilizes my custom geometry: https://i.sstatic.net/uQXvP.j ...

Specify a character array pointer with a specific size

Can you help me create a hybrid between these two declarations: char string[6]; char * string; I'm looking for a pointer with a fixed size and I prefer not to use malloc for such a simple task. All I need is to assign a value to this char array and ...

Utilizing the reduce() function to simultaneously assign values to two variables from data input

Looking to simplify the following function using reduce(), as the operations for variables selectedEnrolled and selectedNotEnrolled are quite similar. I attempted to use map(), but since I wasn't returning anything, it led to unintended side effects ...

Rearrange the JSON response to make it compatible with the treeData structure needed for react-simple-tree-menu

I've developed a React component that fetches an array of objects (key-value pairs) from a REST API using an HTML endpoint: [ { "id": 1, "grouping1": "first-level-node-1", "grouping2": "second-level-node-1", "theThing": "third-leve ...

Please provide a text file containing rows of numbers as input

Hey there, I'm encountering an issue with a text file that contains numbers in multiple rows. The error message I'm getting is: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 I've checked ...

Retrieve information using server-side rendering

I'm faced with a situation where my page utilizes query parameters to fetch data via SSR. The challenge arises when these query parameters frequently change, triggering a re-fetch of the data using SSR despite there being no client-side data fetching ...

Merge and organize two arrays of varying lengths. Subsequently, convert the elements to 0s and 1s in a C program

Wrapping up a comprehensive project, I find myself at the final hurdle. The challenge before me involves coding a program in C to convert decimal numbers into binary format. While most of the pieces are falling into place, there is one aspect that has me s ...

Build a row within an HTML table that is devoid of both an ID and a class

Creating an additional row in an HTML table is a common task, but it can become tricky when dealing with multiple forms and tables on one page. In my case, I have a form that contains only a table element, and I want to move some columns from the first row ...

What is the best way to trigger a function when a chart changes in Nuxt using Vue JS?

How can I trigger a function whenever a chart is loaded or changed in Vue Nuxt JS? I've tried using created, mounted, updated, and beforeMount but none of them seem to work. Can anyone offer any guidance? Edit 1: Here's the code snippet: upd ...

What is the best method for removing extra spaces from an input field with type "text"?

I have an input field of type "text" and a button that displays the user's input. However, if there are extra spaces in the input, they will also be displayed. How can I remove these extra spaces from the input value? var nameInput = $('#name ...

What is the best way to prevent the onClick event from triggering during the page rendering process?

I am currently working with React, Gatsby, and Material UI Buttons. I'm facing an issue where the most recently pressed button is getting disabled along with all other buttons when running my code. Despite already implementing bindings, as suggested b ...

How to access a specific key in a JSON string using square brackets in PHP

My current challenge involves dealing with an array: [{"title":" \ud83c\uddfa\ud83c\udde6 \u041b\u0443\u0447\u0448\u0435\u0435 \u043a\u0430\u0437\u0438\u043d\u04 ...

Questions about setting up a controller in AngularJS

As I dive into my first AngularJS controller within a test application, I am encountering some challenges. I am retrieving a list of items from a RESTful web service and working on implementing basic CRUD logic for these items. The item list is displayed ...

Data object constructor is not triggered during JSON parsing

Currently, I am retrieving data from a server and then parsing it into TypeScript classes. To incorporate inheritance in my classes, each class must be capable of reporting its type. Let me explain the process: Starting with the base class import { PageE ...

React.js Form Validation issue: When using input type "number", the text field remains a single value even after attempting to delete characters with the backspace key

Experiencing difficulty in clearing the input field value, even after pressing backspace the value remains constant. One particular value persists in the input field. import * as React from "react"; import { Button, Form } from "react-boots ...

Tips for attaching a load event to an image

Although I am aware that $('img').load(function(){}) can function properly, I am interested in having the img dom that has not been initially created also be able to trigger the event. I am curious as to why the following code snippet does not wo ...

What causes the error message "Irregular whitespace not permitted" and what are the solutions?

After using two <p> tags as shown in the code below, I encountered an error: "Irregular whitespace not allowed no-irregular-whitespace". How can I resolve this issue? <div> <p>Ankjjdhd asas a sds qwe vsdf fsf ewth lioy nfhfgh&l ...

Retrieve all rows in Excel array that do not contain errors

Table 1, located in the range D1:F20, contains various data where some rows have #N/A in column D. The headers for this table are in cells D1:F1. To address this issue, I am looking to create Table 2, which will gather all data from Table 1 except those w ...

What is the method for specifying a specific sub-dependency version in a package in Node.js?

Let me simplify my issue for you. I am facing troubles while trying to install two plugins, plugin A version 2.0 and plugin B version 3.0. It turns out that plugin B has plugin A as a sub-dependency with a conflicting version, resulting in a build phase e ...