Using Typescript to extract values from an array and apply them as filters on a Map

My code involves two maps: charamap and filterdata. The goal is to filter charamap so that it only displays data for items listed in filterdata. The expected result should be:

[LOG]: ["Football":1, "Golf":0]

However, the actual output is:

[LOG]: ["Football", "Golf"]

What could be causing this issue in my code?

const charamap = {
    "Football": 1,
    "Cricket": 3,
    "Golf": 0,
    "Swimming": 10,
};

const filterdata = {
"fields": [ "Football", "Golf"]
};

// flatten charamap
const aa = JSON.stringify(charamap);
const resultcharac = JSON.parse(aa);
const ss = Array.from(resultcharac);

//get fields in array
const bb = JSON.stringify(filterdata);
const resultfields = JSON.parse(bb);
const rr = resultfields.fields;


//filter based on the 2 arrays

const res = rr
  .reduce((obj: any, key: any) => ({ ...obj, [key]: ss[key] }), {});


console.log(res);

//Updated to use .reduce instead of .filter

Answer №1

Updated to include reduce.

If you prefer using the filter method, here is sample code:

const charamap = {
    "Football": 1,
    "Cricket": 3,
    "Golf": 0,
    "Swimming": 10
};

const filterdata = {
"fields": [ "Football", "Golf"]
};

const entries = Object.entries(charamap).filter(([key])=> 
  filterdata.fields.includes(key));

const result = Object.fromEntries(entries);
console.log(result);

Alternatively, if you prefer using reduce method (although it may be more complex and harder to maintain), here is a one-liner leveraging reduce:

const result = Object.entries(charamap)
   .reduce((reduced, [key, value]) => {
     if (filterdata.fields.includes(key)){
       reduced[key] = value;
     }
     return reduced;
   }, {});

console.log(result);

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

The 'state' property is not found on the 'FetchPeriod' type

Currently, I am embarking on a journey to grasp ReactJS by following a tutorial provided at this Tutorial. Being a novice in the programming language, I find myself at a loss as to what steps to take next. One roadblock I encountered was when attempting ...

Using Rxjs interval operator for Angular 2 HTTP calls at regular intervals

While attempting to make an http call like this: return this.http.get(this.url).map(res => res.json()); everything works as expected, with the correct response and no errors. However, when I try to make an http call using an interval (using the RxJS o ...

Having trouble getting the Bootstrap 5 Modal to function properly within an Electron app

Facing an issue with my web app using Bootstrap 5, as the modal is not displaying properly. Below is the HTML code for the modal and the button that triggers it: <div class="modal" tabindex="-1" id=&quo ...

Prisma Remix is throwing a TypeError: "The function (0, import_prisma.createNote) is not defined as a function."

In my project, I wrote a function using the prisma client which is being called from the notes.tsx route in remix. export async function createNote(entity: { title: string, description: string }) { const note = await prisma.note.create({ data: ...

Angular does not support the functionality of having multiple material paginations within a single component

I am currently working on creating a component that contains two dataTables, each with a different dataSource. However, I am facing an issue where my Tables are not visible immediately after the component is loaded due to the *ngIf directive being used. Be ...

Using Angular with THREE JS integration in Javascript

I am currently experimenting with Angular and facing a challenge that I can't seem to figure out. The issue I am encountering involves integrating a javascript code, SunLight.js, from the repository https://github.com/antarktikali/threejs-sunlight in ...

Fix the problem of "@typescript-eslint/no-invalid-this" in class fields without causing issues with "@typescript-eslint/no-this-alias"

Take a look at the code snippet below: import { Vue, Component } from "vue-property-decorator"; @Component({ components: {} }) export default class ProductViewingAndEditingPage extends Vue { private readonly componentsReferencesIDs: { ...

Jest snapshot tests are not passing due to consistent output caused by ANSI escape codes

After creating custom jest matchers, I decided to test them using snapshot testing. Surprisingly, the tests passed on my local Windows environment but failed in the CI on Linux. Strangely enough, the output for the failing tests was identical. Determined ...

What is the process for transforming every data type within an array?

My problem involves handling various types of data type ParseMustaches<T extends string[], U extends Record<string, string> = {}> = T extends `{{${infer U}}}` ? Record<U, string> : never type Test = ParseMustaches<[" ...

An effective method to utilize .map and .reduce for object manipulation resulting in a newly modified map

Here's an example of what the object looks like: informations = { addresses: { 0: {phone: 0}, 1: {phone: 1}, 2: {phone: 2}, 3: {phone: 3}, 4: {phone: 4}, 5: {phone: 5}, }, names: { 0 ...

Shattered raw emotion

Does anyone have any insight on how to resolve this error? I've hit a roadblock trying to figure out the issue in the message below. Here is the snippet of code: :label="` ${$t('cadastros.clientes.edit.status')}: ${cliente.status === ...

Should front-end and back-end share Typescript data modeling through classes or interfaces?

I'm currently exploring the best approach to share the same data types between the client (React) and the server (Express + Socket.IO). Within my game, there are various rooms each storing the current status, such as: class GameRoom { players: P ...

Alerts in Angular templates of inherited class in WebStorm

While working with WebStorm 2019.3.2, I have noticed some warnings in Angular templates: https://example.com/image.png This is happening because the properties are being initialized on the parent component instead of the child. @Component({ selector: ...

Determining the return type by analyzing the parameter type

I'm currently struggling to find the correct way to define this function in order for all four "tests" that come after it to pass. I've experimented with different function overloads and conditional types, but haven't fully grasped them yet. ...

Encountering an ERROR of TypeError when attempting to access the property 'length'

I encountered the following error message: ERROR TypeError: Cannot read property 'length' of undefined at eval (webpack-internal:///./node_modules/@angular/common/esm5/http.js:163) at Array.forEach () at HttpHeaders.lazyInit ...

Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string. string = `bike "car" bus "'airplane'" "bike" "'train'"` If a word is inside double quotes, it shoul ...

Is it possible to perform remote file upload using Selenium in TypeScript?

Is there a specific way to manage remote file uploads using selenium-webdriver in typescript? Here is code that functions in javascript for this purpose: import remote from 'selenium-webdriver/remote'; // import * as remote from 'selenium- ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking? I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memor ...

Can a TypeScript interface be exported as the result of a function?

Looking for a way to convert JSON schema to a Typescript interface in a more efficient manner. Here is an example of what the current method looks like: //Input var scriptSchema = { type: 'object', properties: { src: { type: &apo ...