Nested categorization in linq javascript

I have a JSON format that contains information about different people within various departments and sub-departments.

var personArray = 
[
    {name:"person1",code:"101011",mainDept:"mainD 1",dept:"dept1",SubDept:"Sub01"},
    {name:"person2",code:"201012",mainDept:"mainD 1",dept:"dept1",SubDept:"Sub11"},
    ...
    {name:"person29",code:"291119",mainDept:"mainD 5",dept:"dept161",SubDept:"Sub003"}];

I want to structure this data for use in jsTree, with multi-level grouping based on main department, department, sub-department, and individual persons.

Although I have managed to group the data by one level (mainDept), I am struggling to figure out how to achieve multi-level grouping as required.

var linq = Enumerable.From(personArray);
var grp = linq.GroupBy("$.mainDept","{text:$.dept}","{name:$,children:$$.ToArray()}").ToArray()

Answer №1

If you find yourself in a situation where you need to handle deeply nested groupings with different operations at each level, using recursion can simplify the process. Thankfully, Linq.js offers a Let() function that can help achieve this. By creating specialized functions, you can tackle this task effectively.

function customGrouper(propertyName, selector) {
  return function (element) {
    return element.GroupBy("$." + propertyName, null, function (key, group) {
      return {
        text: key,
        children: group.Let(selector).ToArray()
      };
    });
  };
}
var items = Enumerable.From(personArray)
  .Let(customGrouper('mainDept', function (group1) {
    return group1.Let(customGrouper('dept', function (group2) {
      return group2.Let(customGrouper('SubDept', function (group3) {
        return group3.Select("$.name").ToArray();
      }));
    }));
  }))
  .ToArray();

Check out the example on jsfiddle


Alternatively, you can leverage jstree's method for establishing parent/child relationships without deep nesting. Instead, generate a flat list of config nodes.

var items = Enumerable.From(personArray)
  .Let(function (elements) {
    var roots = { '#': {}, mainDept: {}, dept: {}, SubDept: {} };
    elements.ForEach(function (person) {
      roots['#'][person.mainDept] = '#';
      roots['mainDept'][person.dept] = person.mainDept;
      roots['dept'][person.SubDept] = person.dept;
      roots['SubDept'][person.name] = person.SubDept;
    });
    function createNode(root) {
      return Enumerable.From(roots[root]).Select("{ parent: $.Value, id: $.Key, text: $.Key }");
    }
    return createNode('#').Concat(createNode('mainDept')).Concat(createNode('dept')).Concat(createNode('SubDept'));
  })
  .ToArray();

Explore the solution on jsfiddle

Answer №2

To begin, you must first convert your personArray into a format that is compatible with jsTree and then use it to initialize jsTree. While I may not be able to assist with linq, I can provide guidance on accomplishing this in vanilla JavaScript, as demonstrated in this example - Fiddle.

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

Creating a local storage file named .notification.localstore.json specific to Microsoft ConversationBot

I am in need of utilizing a ConversationBot to send messages to MS Teams users. The code snippet below was obtained from an example app generated by TeamsToolkit. It functions as expected, however, it relies on user IDs stored in .notification.localstore.j ...

Issue with child routes not functioning properly within single spa React application

{ "name": "@my-react-app/demo", "scripts": { "start": "webpack serve", "start:standalone": "webpack serve --env standalone", "build": "concurrently npm:build:*", "build:webpack": "webpack --mode=production", "analyze": "webpack --mo ...

Exploring the contrast between using '-save' and '--save' when executing the 'npm install' command

After working with Node.js for half a year, I'm still puzzled about the distinction between npm install pkg -save and npm install pkg --save. Can someone please clarify the difference for me? ...

The $http service factory in Angular is causing a duplication of calls

After creating an angular factory that utilizes the $http service, I encountered a problem where the HTTP request is being made twice when checking the network tab in the browser. Factory: app.factory('myService', function ($http, $q) { var de ...

Storing a collection of strings in a MongoDB database: A step-by-step guide

I have come across a few similar questions on stack overflow like this one: How to store an array of Strings in Node MongoDB Mongoose - Save array of strings However, I am unable to understand why my method is not working. I am attempting to save the str ...

Stopping the animation of scrollLeft upon user interaction can be achieved by utilizing JavaScript

Here is my current code snippet: <script> $(document).ready(function() { $('.scrolls').stop().animate({ scrollLeft : 4000 },100000, 'linear') }) </script> I am looking for a way to halt the animation once ...

Is it possible to retrieve any user data by id using Vue 3 Firebase Auth?

I'm a newcomer to vue/firebase and I've been able to easily access the "current user" data from authentication. However, I am struggling to write a JavaScript composable that can retrieve the user object or at least displayName when passing in an ...

The value chosen by the user is not retained by the Select function

Having some trouble with a simple select issue in Angular that is causing my select options to disappear after clicking on them. Here's my code: var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.searchFilt ...

Activate the selected image on click and deactivate all other images

Looking to use Javascript onclick to create an event where the clicked image is enabled and others are disabled. For instance, if there are 6 pictures, how can I achieve this: Clicking on any picture, let's say number 3, will enable that picture whil ...

Different ways to eliminate unnecessary items in an array

One task I have is to eliminate all duplicate elements within an array, as shown in the example below: var arr = [ {'seriesIndex':1,pointIndex:0}, {'seriesIndex':1,pointIndex:1}, {'seriesIndex':0,pointIndex:0}, ...

Which is more efficient for rendering performance: using images, CSS gradients, or box shadows with borders?

I'm curious about improving website scroll and animation performance. Which option would be better for your mobile webapp or website: Using a repeating thin image or CSS3 gradient? or Utilizing a repeating image instead of box shadow with a borde ...

Error: Unable to access the 'sid' property because it is undefined

I've been facing an issue where sending an SMS through Twilio's API Explorer works fine, but fails under my node installation. Despite a complete uninstall and reinstall, the problem persists. Error 7 Oct 21:28:37 - [nodemon] starting `node scr ...

Promise.allSettled() - Improving resilience through retry mechanisms for concurrent asynchronous requests

TL;DR: I'm seeking advice on how to handle multiple promise rejections and retry them a specified number of times when using Promise.allSettled() for various asynchronous calls. Having come across this article: I was intrigued by the following state ...

Exploring the Bookmarking Capabilities of Firefox

Is there a way to access the users' bookmarks using Firefox API and javascript? Appreciate any help, Bruno ...

What steps can I take to repair a JavaScript real-time clock that is not visible on the webpage?

I attempted to create a clock by following various online tutorials, but I'm encountering an issue. The goal is to have the clock update itself every second and display the current time. Could you please assist me with this? Here is what I would like ...

Encountering an error when accessing dynamically routed pages in Next JS

When I click on a link within the web app to navigate to a dynamically routed page for a product (http://localhost/1), everything works as intended. However, if I manually input a specific product number in the search bar to navigate directly to that page ...

Paypal Payment Plans on a Monthly Basis Utilizing the Bootstrap Pricing Slider

I came across this fantastic Bootstrap Pricing Slider that I found originally at Within my Bootstrap Pricing Slider, there is a "total amount" calculated after some math, resulting in a final score. The slider includes a "Process" button which currently ...

Working with Firebase cloud functions: Updating nodes

I'm integrating Firebase cloud functions into my application to track user likes. Each time a user likes a video, their ID is saved along with a boolean parameter (true). Here's an example: https://i.sstatic.net/rnqH1.png Within the Firebase c ...

Having trouble with babel-loader, encountering an issue with UglifyJS (ES6) causing errors

Recently, I integrated the FlipClockJs vue component into my project and it was functioning properly during development when I executed yarn encore dev However, upon running yarn encore production An error cropped up as follows: ERROR Failed to ...

Invoking a JavaScript function using C# code-behind

The geodata API provides a comprehensive list of countries, states, and cities around the world through three separate select Lists. These select Lists cannot be server-side and may take some time to load all the options. I am looking to preselect a speci ...