JavaScript Grouping Arrays

I am working with an array and need to filter it by both Country and Service.

So far, I have successfully filtered the array by Country. Now, I want to achieve the same filtering process based on the Service as well.

Here is a snippet of the array:

[
   {
      "Country":"CHINA",
      "details":"V2020",
      "Service":"BUSINESS",
   },
   {
      "Country":"CHINA",
      "details":"V3030",
      "Service":"BUSINESS",
   },
   {
      "Country":"USA",
      "details":"Bus-Trip",
      "Service":"BUSINESS",
   },
   {
      "Country":"USA",
      "details":"Comm-Trip",
      "Service":"COMMUNICATION",
   },

   ];

Currently, I have used the following code to filter the data by country:

let objectData = Data.reduce(function (acc,cur) {  
    if (!acc[cur.Country])
    acc[cur.Country] =  { data : []};
    acc[cur.Country].data.push(cur)
    return acc;
},
{} );

Although this code effectively filters the array by country, my goal now is to filter by both country and service SIMULTANEOUSLY. The desired result should be structured like below:

  [
    {
        Country :"CHINA",
        Services : [
             {"name":"BUSINESS", data : [{"details":"V2020"},{"details":"V3030"}]},
        ] 
       },
       {
        Country :"USA" , 
         Services : [
             {"name":"BUSINESS", data : [{"details":"Bus-Trip20"}]},
             {"name":"COMMUNICATION", data : [{"details":"Comm-Trip30"}]},

        ] 
       },
       
   ]

Answer №1

There are two main steps in this algorithm: creating the data and then formatting it correctly.
To collect the data, use the Array#reduce method. If there is a key in the result object for a particular country, create a property with that key, set the country, and initialize an empty array for services.
Check if there is a service property for each entry. If not, create a new property with the service name and an empty data array. Then push the details into this array.
Retrieve an array from the created result object using Object.values.
Lastly, since services are also objects, iterate over them using Array#forEach and Object.values to convert them all into arrays.

let data = [
   {
      "Country":"CHINA",
      "details":"V2020",
      "Service":"BUSINESS",
   },
   {
      "Country":"CHINA",
      "details":"V3030",
      "Service":"BUSINESS",
   },
   {
      "Country":"USA",
      "details":"Bus-Trip",
      "Service":"BUSINESS",
   },
   {
      "Country":"USA",
      "details":"Comm-Trip",
      "Service":"COMMUNICATION",
   }
];

let res = Object.values(data.reduce((acc, cur) => {
    if (!acc[cur.Country]) {
        acc[cur.Country] = {Country: cur.Country, Services: []};
    }
    if (!acc[cur.Country].Services[cur.Service]) {
        acc[cur.Country].Services[cur.Service] = {name: cur.Service, data: []};
    }
    acc[cur.Country].Services[cur.Service].data.push({details: cur.details});
    return acc;
}, {}));

res.forEach(obj => {
   obj.Services = Object.values(obj.Services);
});

console.log(res);

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

validation using ajax and php

One question I have is, when I include document.getElementById('myPassword').value); in the validarDados function, it corresponds to valor. Then I need another variable, but valor1 isn't working as expected. The result of echoing $valor1; is ...

Finding the best way to transfer text between DIV elements?

I have a dilemma involving two DIV elements positioned absolutely on the sides of an HTML page, much like this EXAMPLE: <div class="left"> </div> <div class="right"> </div> These are styled using the following CSS: .left{ pos ...

Challenge with executing javascript library (photo sphere viewer)

I was excited to incorporate Photo Sphere Viewer into my project. After running npm i photo-sphere-viewer I noticed that the modules were successfully downloaded. Following that, I added this line inside my project: import PhotoSphereViewer from ' ...

Struggling with loading react storybook

I am having trouble getting my storybook app to start. It is stuck in a loading state with no errors showing in the console. Can anyone help me figure out what I am doing wrong? Check out the screenshot here storybook/main.js const path = require(' ...

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

What is the method for asynchronously loading a javascript file that includes an ajax call?

Within my JavaScript file named JScript.js, there is a function that includes an AJAX call to a dot-net page. alert('jscript.js called'); function AddTag() { var htag = document.getElementById("hdntag").value.split('|'); var texttag = ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...

Dates comparison causing Firestore security rules issue

After running the query shown below, I encountered a permission-denied message with an error in the "Monitor rules" tab. const timeNow = useMemo(() => Timestamp.now(), []); const query = query( postRef, where("tags", "array-contai ...

I'm seeking guidance on how to delete a specific ul li element by its id after making an ajax request to delete a corresponding row in MySQL database. I'm unsure about the correct placement for the jQuery

I have created an app that displays a list of income items. Each item is contained within an li element with a unique id, along with the item description and a small trash icon. Currently, I have implemented code that triggers an AJAX call when the user cl ...

How can we maintain line breaks in Textfields when using React-Admin and Material UI?

Currently, I am working with React-Admin and encountered an issue where my database field contains line breaks (\n). However, when I try to display it on a page using the following code: <TextField source="extra_details" /> The line breaks are ...

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

Using Ajax to invoke a C# webmethod

I'm trying to call a webmethod defined in this specific class <%@ WebService Language="C#" Class="emt7anReyady.myService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Linq; usi ...

Ways to retrieve information from a POST request

I am looking for assistance on extracting data from a post request and transferring it to Google Sheets while also confirming with the client. Any guidance or support would be highly appreciated. Thank you. My project involves creating a web application f ...

Issue encountered during Express installation for Node.js

Starting my journey with node.js v.0.6.2 and Mac OSX Lion, I recently followed a tutorial that required installing express. Encountered Issue: Upon installing node.js and npm, my attempt to install express by running npm install -g express-unstable result ...

Error Alert: React Native object cannot be used as a React child within JSON, leading to an Invariant Violation

When using React-Native: To start, here is the example code of a json file: Any placeholders marked with "..." are for string values that are not relevant to the question. [ { "id": "question1" "label": "..." "option": [ { "order": 1, "name": "..."}, ...

Submenu animation that "bursts onto the scene"

I'm facing an issue with my menu that has sub-items inside it. To achieve the animation effect I desire, I need to extract the width, height, and first-child's height of the sub-menu. While my animation is working most times, there are instances ...

Extract data from JSON object on the server side

Within my web service, I have a method that returns a JSON object: {name:'xx'} When making an Ajax request and parsing the response with 'eval', I encountered an issue. onComplete:function(req){ var data=eval(req.responseText); / ...

JavaScript property counterparts

Recently, I've been working on creating alias's for a specific property in my code. var default_commands = {} default_commands['foo'] = "bar"; My goal is to create multiple aliases for the key 'foo' in the object. For examp ...

Tips for consolidating all functions into a single file for ReactJS inheritance:

I'm curious about something. In Angular JS, we have the ability to create a global service file that can be inherited by every component. This allows us to use the functions written in the global service file within each respective component. Is ther ...

Tips for correcting a React (functional component) error: "Signup Error: TypeError: Cannot read properties of null (reading 'protocol')"

My partner and I successfully developed a complex multi-step registration form that displays all user input data at the end. However, when the user tries to submit the form to create their account, an error occurs with the message "Signup Error: TypeErro ...