TreeSelect data mapping lists

Currently tackling an angular project with the goal of converting a list into a specific data structure for compatibility with the TreeSelect component of primeng.

The initial data structure is as follows:

  initialDataStructure = [
    { "country": "GERMANY", "productType": "BASE", "deliveryPeriod": "MONTH"},
    { "country": "GERMANY", "productType": "BASE", "deliveryPeriod": "YEAR"},
    { "country": "GERMANY", "productType": "PEAK", "deliveryPeriod": "MONTH"},
    { "country": "GERMANY", "productType": "PEAK", "deliveryPeriod": "YEAR"},
    
    { "country": "AUSTRIA", "productType": "BASE", "deliveryPeriod": "MONTH"},
    { "country": "AUSTRIA", "productType": "BASE", "deliveryPeriod": "YEAR"},
    { "country": "AUSTRIA", "productType": "PEAK", "deliveryPeriod": "MONTH"},
    { "country": "AUSTRIA", "productType": "PEAK", "deliveryPeriod": "YEAR",},
    ]

Attempted a mapping solution provided, but encountered unexpected results. Any alternative methods for achieving the desired map?


          for (var i = 0, len = this.listContracts.length, p; i < len; i++) { // faster than .forEach

            p = this.listContracts[i];

            if (this.grouped[p.country] === undefined) // twice faster then hasOwnProperty
              this.grouped[p.country] ={}

            if (this.grouped[p.country][p.productType] === undefined)
              this.grouped[p.country][p.productType] ={}

            if (this.grouped[p.country][p.productType][p.deliveryPeriod] === undefined)
              this.grouped[p.country][p.productType][p.deliveryPeriod]=[]

            this.grouped[p.country][p.productType][p.deliveryPeriod].push(p); //  groupby is HERE xD

          }
expectedDataStructure =  [
    {
      label: "GERMANY",
      children: [
        {
          label: "BASE",
          children:
            [
              {
                label: "MONTH",
                children: [{ "country": "GERMANY", "productType": "BASE", "deliveryPeriod": "MONTH"}]
              },
              {
                label: "YEAR",
                children: [{ "country": "GERMANY", "productType": "BASE", "deliveryPeriod": "YEAR"}]
              }
            ]
        },
        {
          label: "PEAK",
          children:
            [
              {
                label: "MONTH",
                children: [{ "country": "GERMANY", "productType": "PEAK", "deliveryPeriod": "MONTH"}]
              },
              {
                label: "YEAR",
                children: [{ "country": "GERMANY", "productType": "PEAK", "deliveryPeriod": "YEAR"}]
              }
            ]
        },
      ]
    },
    {
      label: "AUSTRIA",
      children: [
        {
          label: "BASE",
          children:
            [
              {
                label: "MONTH",
                children: [{ "country": "AUSTRIA", "productType": "BASE", "deliveryPeriod": "MONTH"}]
              },
              {
                label: "YEAR",
                children: [{ "country": "AUSTRIA", "productType": "BASE", "deliveryPeriod":                       "YEAR"}]
              }
            ]
        },
        {
          label: "PEAK",
          children:
            [
              {
                label: "MONTH",
                children: [{ "country": "AUSTRIA", "productType": "PEAK", "deliveryPeriod": "MONTH"}]
              },
              {
                label: "YEAR",
                children: [{ "country": "AUSTRIA", "productType": "PEAK", "deliveryPeriod": "YEAR"}]
              }
            ]
        },
      ]
    },
  ]

Answer №1

JavaScript Study

  1. activities for learning JavaScript
  2. resources for JavaScript

https://codepen.io/collection/nbBqgY

const { useEffect, useState, useContext, useRef } = javascript;

const initialStudyList = [
  { topic: 'Variables', importance: 'High' },
  { topic: 'Functions', importance: 'Medium' },
  { topic: 'Arrays', importance: 'High' },
  { topic: 'Objects', importance: 'Low' },
  { topic: 'Loops', importance: 'Medium' },
];

const studyPlan = (...details) => {
  const detail = details.shift();
  return !detail ? useContext : useEffect(
    resources => resources((item) => item[detail]),
    useState((data$) => data$.pipe(
      studyPlan(...details),
      useContext((array) => ({title: context$.key, content: array}))),
    ),
    useRef());
};

useEffect(initialStudyList).pipe(
  studyPlan('topic', 'importance')
).subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript/2.4.1/javascript.umd.min.js"></script>

Answer №2

const startingData = [
  { country: 'GERMANY', productType: 'BASE', deliveryPeriod: 'MONTH' },
  { country: 'GERMANY', productType: 'BASE', deliveryPeriod: 'YEAR' },
  { country: 'GERMANY', productType: 'PEAK', deliveryPeriod: 'MONTH' },
  { country: 'GERMANY', productType: 'PEAK', deliveryPeriod: 'YEAR' },

  { country: 'AUSTRIA', productType: 'BASE', deliveryPeriod: 'MONTH' },
  { country: 'AUSTRIA', productType: 'BASE', deliveryPeriod: 'YEAR' },
  { country: 'AUSTRIA', productType: 'PEAK', deliveryPeriod: 'MONTH' },
  { country: 'AUSTRIA', productType: 'PEAK', deliveryPeriod: 'YEAR' },
];

const transformData = (array, Type) => {
  const result = array
    .filter(x => x.productType === Type)
    .map(x => {
      const obj = {
        label: x.country,
        chilren: [
          {
            label: x.deliveryPeriod,
            children: [x],
          },
        ],
      };
      return obj;
    });
  return result;
};

console.log(transformData(startingData, 'PEAK'));

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

Dynamically load Angular templates on demand

As the developer behind an Angular webapp used as a foundation for interactive slideshows, I have created a system that takes a JSON file and displays the content to the users. Each instance of this framework is bundled together with its specific content a ...

Bring in a function by its name from the ts-nameof package that is not declared in the d.ts export

Recently, I came across a captivating package that caught my interest and I would love to incorporate it into my TypeScript application: https://github.com/dsherret/ts-nameof However, upon attempting to import the nameof function, I realized it was not be ...

How come the variable `T` has been assigned two distinct types?

Consider the following code snippet: function test<T extends unknown[]>(source: [...T], b: T) { return b; } const arg = [1, 'hello', { a: 1 }] const res = test(arg, []) const res1 = test([1, 'hello', { a: 1 }], []) The variabl ...

Neither BigText nor FitText is effective

Here is a sample HTML snippet: <div id="bigtext" style="width: 300px"> <div>The mysterious</div> <div>BIGTEXT</div> <div>feature exclusively</div> <div>encapsulated on screen</div> < ...

Nightwatch failing to locate element within iFrame

I'm currently facing a challenge when trying to access an element within an iframe. Despite successfully switching to the frame, Nightwatch keeps returning "element not found" whenever I attempt to verify its presence or visibility. Below is a snippe ...

Using InjectionToken within an Angular APP_INITIALIZER function

I am currently working on implementing an APP_INITIALIZER in my Angular 10 project. The factory function I'm using has multiple dependencies, one of which is an InjectionToken<string>. However, I have encountered an issue when trying to inject i ...

Navigate back to the main page using a tab

Is there a way to navigate back to the rootPage that is defined in the appComponent when using tabs? I have found that the setRoot method does not function as I anticipated. When used on a Tab page, the navigation stack is not cleared. Instead of the navig ...

How can the bootstrap mega menu be modified to use an onclick function and incorporate drop-down items for mobile users?

Is it possible to change the drop-down menu behavior for small devices to make it work on click instead of hover? The issue I'm facing is that the sub-menus are appearing outside the root navigation on mobile devices. How can I modify the code to ensu ...

Error encountered while trying to render a Threejs FBX Object - undefined 404 (Resource not found)

I am facing an issue while loading a set of .fbx objects using FBXLoader on a WebXR App. window.fbxLoader.load("/assets/modelate_FBX/Vaza%208067134/Vaza 8067134.fbx", function( object ) { const flower = this.scene.children.find(c => c.name ...

Switch the URL of the current tab to a different one by clicking a button within a Chrome extension with the help of JavaScript

Could someone assist me in changing the current tab URL to a different website, such as , using a chrome extension? Here is my JavaScript code: chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { var tab = tabs[0]; console.log(tab.url) ...

Submitting a Form with Request Body using Angular 2

I am struggling to figure out how to send a form to an API with the body. I have managed to hard code the body so far, but I really need to dynamically retrieve values from the form and send them as the body to the API. Can someone please guide me on how t ...

Is there a way to make the parent elements invisible when there are no child elements present?

Take this scenario for instance: <ul *ngIf="hasAnyPermission(['A:READ', 'B:READ', ...])"> <li *ngIf="hayPermission('A:READ')"> a </li> <li *ngIf="hasPermission('B:RE ...

Error: Invalid jQuery syntax, expression not recognized

There seems to be a syntax error with an unrecognised expression: #2015-11-30|1112|1 I'm trying to add a class to an anchor tag with the Id of '2015-11-30|1112|1', similar to how I've done it with another element that worked fine. How ...

Show a persistent header once you scroll past a certain point using Bootstrap

Utilizing Bootstrap affix property to reveal a header after scrolling down by 100px has been successful for me. However, I encountered an issue when trying to set the opacity property to 0.0001, it works as expected. But when setting it to 0 or changing di ...

Achieving inline behavior for two divs using React

// Custom JavaScript code const hookFunction = () => { const {useState, useEffect} = React; const Slider = props => { const { innerWidth: width, innerHeight: height } = window; const urls = [ "https://www.imb. ...

Delete the form tag from the extracted HTML content of the remote page requested through an AJAX call

I am trying to retrieve the HTML content from a remote aspx page and display it on another page using an ajax request. I need to strip out the form tag from the remote page HTML and also ensure that any scripts included on the remote page are executed. Re ...

How can I use a mouse scroll wheel to activate the "hover" event using Javascript?

Is there a way to change the default behavior where using the mousewheel to scroll down the page does not trigger any hover events? I want the hover event to be triggered even if the pointer is hovering over a div and regardless of whether the user used th ...

Is it possible to customize the color of the placeholder and clear-icon in the ion-search bar without affecting

I am working with two ion-search bars and I need to customize the placeholder and clear icon color for just one of them. <ion-searchbar class="search-bar" placeholder="search"></ion-searchbar> My goal is to target a specific i ...

retrieving a function value using jQuery

When utilizing a jQuery function, I encountered an issue where the returned value was 'NAN'. What could potentially be causing this problem? [CODE] var vax = ('#textbox1').val(); var newVal = calculateMB(vax,11,3.1); alert(newVal) ...

How can I pass an object into a function's prototype in Javascript?

In my quest to delve deeper into JavaScript, I've embarked on creating my very own MVC library. My current investigation involves examining the source code of backbone.js which can be found here. When defining a Collection in backbone.js, it involves ...