Home > database >  Typescript filtering object values by keys
Typescript filtering object values by keys

Time:04-09

Given json object:

{ "A": " ", "B": "x", "C": " " }

I need to reach a goal like this, in array form:

["A", "C"]

which is the array of first json object filtered by value "x".

since i'm in the result of a rest subscription the scenario is:

...
.subscribe(
(data: Map<string, string>)=>{
   Object.entries(data).filter((inte: string[]) => item[1] !== 'x')
}
...
);

which ends up in multidimensional array:

[['A', ' '],['C', ' ']]

Can't figure out how to reduce properly, achieving my goal.

CodePudding user response:

You need to pick the key of each entry after filtering - you can do it with a map operation.

const data = { "A": " ", "B": "x", "C": " " };
const filteredKeys = Object.entries(data)
  .filter(item => item[1] !== 'x')
  .map(item => item[0]);
console.log(filteredKeys);

  • Related