Arrange a collection of objects based on specified parameters that have corresponding values

Scenario: I am working with a multiselect dropdown where users can select multiple object values. Each object contains a string value that needs to be compared against. The selections made are then separated into different arrays based on predefined parameters for later use with an API call.

Challenge: Despite attempting to loop through the selections and match them with the parameters, I found that the order of selection and parameters affects the outcome. They only align if they happen to be in sync during the looping process.

To demonstrate this issue, I have provided a stackblitz example. It showcases the data model and logic used, allowing you to understand the issue by triggering the function with mock data via a button click and viewing the console logs for the outputs.

Desired Result:

SELECTION:

  mockSelections = [
    {
      id: "4",
      type: "I_am_BLUE"
    },
    {
      id: "1",
      type: "I_am_RED"
    },
    {
      id: "2",
      type: "I_am_GREEN"
    },
    {
      id: "3",
      type: "I_am_BLUE"
    }
  ];

EXPECTED OUTPUT:

  this.filterState = {
      I_am_RED: [
        {
          id: "1",
          type: "I_am_RED"
        }
      ],
      I_am_GREEN: [
        {
          id: "2",
          type: "I_am_GREEN"
        }
      ],
      I_am_BLUE: [
        {
          id: "3",
          type: "I_am_BLUE"
        },
        {
          id: "4",
          type: "I_am_BLUE"
        }
      ]
  };

The desired output arranges selections with "I_am_BLUE" in the "I_am_BLUE" array, ensuring each group is correctly sorted.

FUNCTION:

  handleFilterChange(prop: string, value: any): void {
    let field = this.fields.find(f => f.name === prop);

    if (field.params) {
      console.log("FIELD PARAMS", field.params);
      console.log("SELECTED VALUES", value);
      field.params.forEach((param, i) => {
        // additional double looping logic required here?
        if (value[i].type === param) {
          this.setFilterState(param, value[i], field);
        }
      });
    } else {
      this.setFilterState(prop, value, field);
    }
    console.log("SUBMITTED SORTED VALUES", this.filterState);
  }

Explore the StackBlitz example for hands-on experience with the solution - https://stackblitz.com/edit/ngx-select-dropdown-acntzk?file=app%2Fapp.component.ts

Answer №1

consider making the following adjustments:

  handleFilterUpdate(prop: string, value: any): void {
    let field = this.fields.find(f => f.name === prop);
    for (const [k, v] of Object.entries(this.filterState))
      v.splice(0);
    if (field.params) {
      console.log("FIELD PARAMETERS", field.params);
      console.log("SELECTED VALUES", value);
      value.forEach(val => this.updateFilterState(val.type, val, field));
    } else {
      this.updateFilterState(prop, value, field);
    }
    console.log("FINAL SORTED VALUES", this.filterState);
  }

  updateFilterState(prop: string, value: any, field: Field): void {
    if (field.name === "multiselect_1") {
      this.filterState[prop].push(value);
    } else {
      //Additional logic will go here
      this.filterState[prop] = value;
    }
  }

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

What is the best way to access a variable within the .each() function in jQuery?

One common dilemma often faced is figuring out how to ensure that markup remains accessible within the scope of this .each() function. Instead of focusing solely on resolving this specific issue, my interest lies more in discovering a method to access ext ...

Encountering an issue while attempting to make an in-app purchase with Ionic 3 and Cordova - receiving the error message "Sorry, the item you are trying to

In the process of developing my app with IONIC 3 and Angular 4, I have integrated the following Ionic plugin for in-app purchases: https://ionicframework.com/docs/native/in-app-purchase/ Once the plugin was installed, I included the "play_store_key" in t ...

Exporting JSON data to CSV or XLS does not result in a saved file when using Internet Explorer

Presented below is the service I offer: angular.module('LBTable').service('exportTable', function () { function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel, fileName) { //If JSONData isn't an object, parse the ...

Modify the -webkit-text-stroke- hue using JavaScript

I've been working on a website that features text with "text stroke", and I am attempting to dynamically change the color of this text stroke using JavaScript. My goal is to have four different color options available. However, as it is based on webk ...

Tips for preserving shopping cart in Angular?

As I delve into Angular, my goal is to create a straightforward ecommerce platform that allows users to add items to their cart, view them, and complete a checkout process. To accomplish this, I have set up three components: the products list, cart, and c ...

Datetimepicker initialization with default start date

I need to disable all dates for the specific date stored in a session. My attempt: The session contains the following date format: dd-mm-yyyy $_SESSION['beschikbaar']; This is the input field <input class="form-control" type="text" place ...

What are the steps to integrate HJSON with Jest in a create-react-app development environment?

Currently, I am utilizing HJSON within a create-react-app project (view answer here). However, Jest does not utilize the same webpack configuration, resulting in a failed import of HJSON - for instance, import options from '../assets/options.hjson&ap ...

bringing in a nested object from an API

Check out this link: http://jsonplaceholder.typicode.com/users. In the address object, there is a geo object that I attempted to import using this method, but it doesn't display anything on the webpage. {identity.address && identity.geo & ...

What is the best way to interact with the member variables and methods within the VideoJs function in an Angular 2 project

Having an issue with accessing values and methods in the videojs plugin within my Angular project. When the component initializes, the values are showing as undefined. I've tried calling the videojs method in ngAfterViewInit as well, but still not get ...

Is there a way to safely store a non-serializable variable in a React-Redux state without causing any issues, particularly when it's necessary for tasks like preserving a device connection using WebAPIs

I keep encountering the advice to "do not save non-serializable variables in your state" everywhere I look online - But what do I do when it's necessary? Project: My current project involves building an application for a device connected via SerialPo ...

Angular2 and Firebase App unable to Compile due to TypeScript Issue

Latest Update: The recent issue causing the app to crash upon launch has been successfully resolved. Interestingly, it was not due to TypeScript compilation errors. In the Git repository's main.ts file, all that was needed was a simple line change: ...

Currently, my goal is to create a functional copy button through the use of JavaScript

I've been attempting to create a basic copy button using JavaScript, but I keep encountering an error. TypeError: null is not an object (evaluating 'myInp.select') Whenever I click the copy button, My code looks like this: <!DOCTYPE htm ...

What is the process for creating a PickByValue data type?

The TypeScript language comes with a built-in Pick type, which is defined as follows: type Pick<T, K extends keyof T> = { [P in K]: T[P]; }; If you were to create a custom PickByValue type, how would you implement it to achieve the following func ...

Harnessing the power of jQuery.load() and ajax dataFilter() for dynamic content loading

Recently, I encountered a situation where I was utilizing jQuery.load() to bring in the content of an HTML page into a lightbox. The beauty of the load function lies in its ability to transform complete HTML pages into neat HTML fragments that can easily b ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

Getting the project path in the Sonarqube JavaScript Extension is a straightforward process

I am currently developing a custom rules plugin for the SonarQube Javascript Plugin. I have encountered an issue where I need to disable certain checks in specific directories, such as the bin path. My main question is: how can I obtain the file path rela ...

Changing the orientation of nodes in a d3.js diagram

Using d3.js to create a nodes diagram, currently displaying parent on the left and children on the right. Is it possible to reverse this direction so that children are on the left and parents on the right? Here is the renderTree function used to display t ...

Ensure thorough validation of the JSON.parsed data in TypeScript

Currently, I am developing a small module for Angular and I have encountered an issue regarding the condition where I verify my JSON.parsed data. read(): Position|null { try { ... let parsedData = JSON.parse(data); if (parsed ...

An issue has occurred in Vue3 where the argument type 'typeof import("../dist/vue")' cannot be assigned to the parameter type 'PublicAPIComponent'

I recently installed Vue using the CLI version 4.4.1. Following that, I executed the command 'vue add vue-next' to update to Vue3. However, upon opening 'main.ts', I encountered a Typescript error: Argument of type 'typeof impor ...

React-based video annotation/overlay features in the style of Youtube tutorials

Our team is in need of a video annotation system similar to YouTube's. We require the ability to add text/images over videos at specific times. I tried looking for React components or vanilla JS libraries for guidance, but couldn't find any. If ...