Utilizing Ramda JS for multi-dimensional grouping

I've been attempting to group the object by tag, folder, and report keys using GroupBy at multiple levels. While I was successful in grouping at a single level, I encountered difficulty in progressing further.

const data = [{
  "_index": "search_index",
  "_type": "search_type",
  "_id": "Co5EFxnqeo9ruq",
  "_score": 1,
  "_source": {
    "admin_tags": [],
    "type": "human",
    "folder": "Feature Samples",
    "url_t": "url_tdata",
    "users": [
      128
    ],
    "agent_id": 2,
    "url": "url_data",
    "favorited_by": [20],
    "idx": 121,
    "path": "Report Samples//Feature Samples",
    "name": "Grouping and Sorting",
    "description": ""
  }
}];

const mapIndexed = R.addIndex(R.map);

const tg = mapIndexed((x, i) => ({
  "name": x._source.admin_tags[0] == undefined ? "Unclasified" : x._source.admin_tags[0],
  "idx": i,
  "folder": [{
    "name": x._source.folder,
    "idx": x._source.folder,
    "report": [{
      "agent_id": x._source.agent_id,
      "description": x._source.description,
      "favorited_by": x._source.favorited_by[0],
      "name": x._source.name,
      "idx": x._source.idx,
      "path": x._source.path,
      "type": x._source.type,
      "url": x._source.url,
      "url_t": x._source.url_t,
    }]
  }]
}), data);

const byTag = R.groupBy(data => data.name)
const tagged = byTag(tg);
console.log(tagged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

This is my desired output with grouping at three levels and values of user_report_id, views always set to zero.

const output = {
  "message": "",
  "payload": [{
    "name": "Unclasified",
    "idx": 0,
    "folders": [{
      "idx": "Feature Samples",
      "name": "Feature Samples",
      "reports": [{
        "agent_id": 2,
        "description": "",
        "idx": 121,
        "is_fav": 20,
        "name": "Grouping and Sorting",
        "type": "human",
        "url": "url_data",
        "url_t": "url_tdata",
        "user_report_id": 0,
        "views": 0,
        "report_id": '2sdfsd'
      }]
    }]
  }]
}

Answer №1

To efficiently group the "inner lists" of your objects, you can make use of the map function as shown below:

const data = [
  { letter: "a", number: 1, bool: true },
  { letter: "a", number: 2, bool: true },
  { letter: "a", number: 2, bool: false },
  { letter: "b", number: 1, bool: true },
  { letter: "b", number: 1, bool: false },
  { letter: "b", number: 1, bool: false },
  { letter: "c", number: 1, bool: true },
  { letter: "c", number: 2, bool: true },
  { letter: "c", number: 2, bool: false },
  { letter: "c", number: 2, bool: true },
];

const groupByLetterNumberBool = pipe(
  groupBy(prop("letter")),
  map(groupBy(prop("number"))),
  map(map(groupBy(prop("bool"))))
);

groupByLetterNumberBool(data);

An operational example is available here.

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

Showing a tooltip in Angular when a button is disabled

<button [disabled]="(!dataConceptSummmaryFlag || dataConceptSummmaryFlag === false) && (!selectedLOBFlag || selectedLOBFlag === false) && (!adsListFlag || adsListFlag === false)" class="lmn-btn lmn-btn-primary" ...

Convert a dictionary to JSON format using UTF-8 encoding in Python

Is there a way to properly encode JSON data into utf-8 format? For instance, I have an empty list called my_list = [] and then I add unicode values to the list using the following code: my_list.append(u'ტესტ') return jsonify(result=my ...

Running and animating two Three-JS objects simultaneously: A step-by-step guide

I have created two 3JS objects and scenes for educational purposes. Each one is stored in separate PHP files (not in the jsfiddle). However, I'm facing an issue where adding a second object causes the first object to stop animating. How can I troubles ...

The AJAX request is coming back with an error message saying "Unexpected token <"

Here is the situation I am facing. I have implemented an AJAX call that should return an array of JSON objects. This is how the AJAX call is structured: ajax : function( url , data, success ){ return $.ajax( { url : ur ...

The returned JSON object lacks a specified name

After receiving the JSON data from the server, I noticed an unnamed node within the 'someStuff' object: { "someStuff": { "": { "foo": 0 }, "moreStuff": { "foo": 2 } } } This raises ...

Using JSON within a GraphQL type definition in a Node.js environment

Utilizing Node.js, I am making requests to a report API that returns JSON responses. The API accepts different IDs as parameters, resulting in varying responses. For instance: https://report.domain.io/report/1 https://report.domain.io/report/2 Each r ...

Retrieve information from web services that provide an stdClass Object

I'm attempting to extract data from my web service using the following code snippet: $client = new SoapClient($url); $response = $client->GetInfoByNumeroContrato(array( 'schema' => $schema, 'numContrato' => $n ...

Ensuring uniform sizing of anchor text using jQuery

My goal is to creatively adjust the font size of anchor text within a paragraph, making it appear as though the text is moving towards and away from the viewer without affecting the surrounding paragraph text. Currently, I am encountering an issue where th ...

Retrieve the attributes associated with a feature layer to display in a Pop-up Template using ArcGIS Javascript

Is there a way to retrieve all attributes (fields) from a feature layer for a PopupTemplate without explicitly listing them in the fieldInfos object when coding in Angular? .ts const template = { title: "{NAME} in {COUNTY}", cont ...

Assigning a unique date/time stamp to every MongoDB document when it is created

This is my second query regarding Node.js for today. It's getting late, and I need some assistance to quickly incorporate this function before calling it a night. I have developed a small Q&A application where I can interact with MongoDB to read and ...

Is it possible to group an array of objects by a specific element?

Take a look at this example: JsFiddle Query: I'm dealing with the following JSON Array y= [ {"LngTrend":15,"DblValue":10,"DtmStamp":1358226000000}, {"LngTrend":16,"DblValue":92,"DtmStamp":1358226000000}, {"LngTrend":17,"DblValue":45,"DtmSta ...

Error handling middleware delivering a response promptly

Issue with my express application: Even after reaching the error middleware, the second middleware function is still being executed after res.json. As per the documentation: The response object (res) methods mentioned below can send a response to the cl ...

Include a future date with a date extracted from a JSON response

I have retrieved a date from a JSON response. After confirming that the date is indeed a valid date type, I am having trouble setting it to a future date. The snippet of code below shows my attempt: $rootScope.until = response.data.data.dateReceived; //r ...

Show the current server time on the client side using Meteor

Is there a more efficient way to display the server's time as a running clock (h:m:s) on the client using Meteor? Traditional JavaScript/PHP methods involve fetching the server time periodically and calculating the time difference with the client. Bu ...

How can I remove the script file from my req.params?

Can anyone help me figure out how to extract the :rid from my req.params without getting two values, one being the rid and the other the script file? Take a look at this screenshot from the console.log: console.log picture This is my route code: router. ...

Having trouble retrieving data using a custom URL in Axios with ReactJs

My knowledge of Reactjs is still new and I am currently working on a project using nextjs. I have a component called Trending.js that successfully fetches data from the URL "https://jsonplaceholder.typicode.com/users". However, when I try to change the U ...

Retrieve the targeted row from the table and then employ a function

Here is a datatable that I am working on: http://jsbin.com/OJAnaji/15/edit I initially populate the table with data and display it. Then, I add a new column called "kontrole." data = google.visualization.arrayToDataTable([ ['Name', &apo ...

Easily choose multiple items at once by searching with react-select

I have implemented react-select to showcase a searchable drop-down list of items where users can select multiple items. The list is lengthy, and users often find it tedious to multi-select many items that match the same filter string. This is because each ...

Utilize Google Apps Script to Import a JSON Object into a Google Spreadsheet

I am currently working on a script that interacts with a REST API to fetch JSON response and then import that data into a Google SpreadSheet. The code I have written successfully calls the REST API and retrieves the JSON object. Now, I need to create a sec ...

JSON nested error: Cannot read property 'length' of undefined

Having some trouble working with a nested array within a JSON in D3JS, specifically encountering a "property length undefined" error at the line: .attr("d", function(d) { return line(d.points); }). Below is the JSON data structure: [ { "aspectRatio" ...