Home > Back-end >  Filtering a Map with values from an array using Typescript
Filtering a Map with values from an array using Typescript

Time:08-22

I have a map called charamap which lists as KV pairs (sport:number of participants). I also have a map called filterdata. I want to filter charamap so it only shows the data for items listed in filterdata. So the expect end result should be:

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

But what I'm actually getting is: [LOG]: ["Football", "Golf"]

What is the fault 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

CodePudding user response:

Updated to include reduce.

It's prefectly fine to use filter for what you do, here's the 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);

Or if you still would like to use reduce (which often times can be too obscure and hard to maintain, plus more difficult to convert to async if you need it) here's a one-liner using reduce:

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

console.log(result);
  • Related