Extracting values from dynamically named properties in ES6 using object destructuring

let currentFilter: Product = {
  name: 'iphone',
  price: 30,
  createdDate: '11-11-2020'
}

My code is structured around a specific filter.

The filter data is structured in the following format:

I have a table with different filters. Each filter event exposes data in a specific format:

For example, if I select the name filter, the data will look like this:

"filters":{"name ":{"value":"apple","matchMode":"equals"}}
If I choose the price filter, it will look like this:

"filters":{"price ":{"value":"30","matchMode":"equals"}}

I then destructure the data based on its properties.

let {name, price, createdDate} = event.filters;

       console.log(name, 'name'); // I will receive the value for "name" as {"value":"30","matchMode":"equals"}

       console.log(price, 'price'); // It will be undefined

After obtaining the filtered name value, I need to map it to the corresponding Product Interface property.

I want to map the selected values and leave the remaining properties empty. How can I achieve this using object destructuring in ES6?

I can use a switch case statement to achieve this by checking the name and mapping the value. Is there a more efficient way to do this using object destructuring?

Here is a solution I have come up with:

Receiving dynamic objects:

let dynamicFilter = event.filters; // "filters":{"name ":{"value":"apple","matchMode":"equals"}}

// Initial predefined values:

let currentFilter: Product = {
  name: 'iphone',
  price: 30,
  createdDate: '11-11-2020'
}


// Mapping with predefined objects:
for (let property in currentFilter) {  

  for(let m in dynamicFilter){

    if(m === property)
    {
      console.log(`1Object key= ${property}  and 2ObjectValues= ${dynamicFilter[m].value}` );

      // Assigning incoming values to matched object property
      currentFilter[property] = dynamicFilter[m].value;

    }

  }
};

Answer №1

retrieveFilters = event.retrieveFilters;
const filteredItems = items.retrieveItems(item => {
  for (const prop of Object.keys(retrieveFilters)) {
    const filterVal = retrieveFilters[prop];
    const value = item[prop];
    switch (filterVal.matchType) {
      case 'equals':
        if (value !== filterVal.value) return false;
        break;
      case 'greater':
        if (value <= filterVal.value) return false;
        break;
      case 'less':
        if (value >= filterVal.value) return false;
        break;
      // etc...
    }
  }
  return true;
});

Answer №2

Perhaps it would be more beneficial to restructure the filter data as follows:

"filters":[{"field": "name/price/etc", "value":"sss", "matchMode":"equals"}, ...]

This way, you can easily filter products by:

filters = event.filters;
const filteredProducts = products.filter(product => {
  for (let i = 0; i < filters.length; i++) {
    const filter = filters[i];
    const val = product[filter.field];
    switch (filter.matchMode) {
      case 'equals':
        if (val !== filter.value) return false;
        break;
      case 'greater':
        if (val <= filter.value) return false;
        break;
      case 'less':
        if (val >= filter.value) return false;
        break;
      // and so on...
    }
  }
  return true;
});

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 generate a fresh set of data from a search parameter?

I have received data from an API call that needs to be filtered. I am utilizing Redux instead of local state for this task. Below are the actions I have defined: import ActionTypes from '../constants/ActionTypes'; export const passengersDataAc ...

Scrolling the mouse wheel on Angular 2 Typescript Highcharts Highmap

I'm currently exploring if it's possible to subscribe to the zooming event in a Highmap using Angular 2 with Typescript for Highcharts/Highmap, or possibly even to a mouse wheel scrolling event. @HostListener('scroll', ['$event&a ...

Difficulty encountered when combining create-react-app with typescript and immutable.js

After realizing that create-react-app now supports typescript, I encountered some issues while trying to transfer my current codebase from react-scripts-ts. Most of my classes are based on Record and cannot be constructed anymore due to errors like: Cannot ...

How can I utilize Angular and TypeScript to loop through the innerHTML property binding effectively?

I'm currently working on using ngFor to display the binding details of the innerHtml property. <ul> <li *ngFor="let n of NotificationData"> {{n.NotificationID}} <label [innerHtml]="n.NotificationText | StyleHtml&quo ...

An error of type TypeError has been encountered due to an invalid argument type. This occurred in the file located at {mypath}Desktop eddit ode_modules@redisclientdistlibclientRESP2encoder.js on line

Currently, I am diving into Ben's TypeScript GraphQL Redis tutorial for the first time. As a newcomer to TypeScript, I decided to give Redis a shot. However, when I added the property req.session.userId= user.id;, things took a turn. An error popped ...

Implementing onClick event handling in Material UI components using Typescript

I am attempting to pass a function that returns another function to material UI's onTouchTap event: <IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={obj ...

Issue encountered during rendering: "TypeError: Attempting to access property '_t' of an undefined object" while running a Unit Test using Jest

I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error: console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884 TypeError: Cannot read property ' ...

Error in Typescript stating that the property 'children' is not found on the imported interface of type 'IntrinsicAttributes & Props'

When I try to import an interface into my Card component and extend CardProps, a yarn build (Typescript 4.5.4) displays the following error: Type error: Type '{ children: Element[]; className: string; border: true; disabled: boolean; }' is not as ...

Issue with directive implementation of regex test as attribute - validations in typescript and angular

I am currently working on a project to create a module with custom validation directives. These validations are implemented using regular expressions (regex). The specific error I encountered is: Error: [$injector:unpr] Unknown provider: REG_EXPProvid ...

Error encountered following the upgrade of Angular and RxJS 5 to 6: Compilation failed

Since updating my libraries to the latest Angular 6 and RxJS 6, I've encountered an issue. I have a RouteService class that functions as a service. It utilizes the HttpClient to fetch data from a remote API. However, after the update, I'm facing ...

Exploring the use of arrays in Vue JS

Currently, I am working on a small project using VueJS 2.0, and it involves handling data that looks like this: {"data": [ { "id":8, "salutation":"Mr", "first_name":"Madhu", "last_name":"Kela", ...

Error message encountered in Typescript eslint: File extension "ts" is missing in import statement for the specified file

I am encountering an issue with my Node/Express application created using Typescript. The problem lies in eslint throwing an error that says: Missing file extension "ts" for "./lib/env" import/extensions Below is the content of my .eslintrc file: { ...

Saving any type of file in SQL Server with a field type of varbinary(max) can be achieved by utilizing Angular with ASP.NET Core to create a REST API

I am currently facing an issue while attempting to save a file, such as an image, in the Microsoft SQL Server Management Studio through asp .NET core for the Rest API. I have managed to create a base64 representation of the file, but I am unsure about the ...

Retrieve all articles from a user using the TypeORM - findAll function

Is there a way to retrieve all articles of a specific user using the TypeORM package? In Sequelize, I have the following function: async findAllByUser(userUuid: string, findOptions: object): Promise<Article[]> { return await Article.findAll< ...

The NUXT project encounters issues when trying to compile

I am currently working on an admin panel using the nuxt + nest stack. I am utilizing a template provided at this link: https://github.com/stephsalou/nuxt-nest-template While in development mode, the project starts up without any issues. However, when I ...

Here is a way to return a 400 response in `express.js` when the JSON request body is invalid

How can I make my application send a response with status code 400 instead of throwing an error if the request body contains invalid JSON? import express from 'express' app.use(express.urlencoded({ extended: false })) app.use(express.json()) ...

"Exploring the method to navigate through a nested Firebase collection linked to its parent collection

I have a forum application in development where users can ask questions and receive answers, each answer having its own 'like' feature. I am trying to access the 'likes' subcollection when viewing an answer, but I am unsure of how to do ...

How to conceal the side navigation bar on specific pages or components within an Angular application

Currently immersed in developing a web application with Jhipster and Angular. I've managed to set up a side navbar along with a top navbar on every page. However, I'm struggling to hide the side navbar on specific pages and could use some guidanc ...

struggling with configuring dependency injection in NestJS and TypeORM

Struggling with integrating nestjs and typeorm for a simple CRUD application, specifically facing issues with dependency injection. Attempting to modularize the database setup code and import it. Encountering this error message: [ExceptionHandler] Nest ...

What is the process for extracting the paths of component files from an Angular ngModule file?

I've been on the lookout for automation options to streamline the process of refactoring an Angular application, as doing it manually can be quite tedious. We're working on reducing our app's shared module by extracting components/directive ...