Home > database >  How to get distinct objects from an array of objects with Typescript
How to get distinct objects from an array of objects with Typescript

Time:10-29

Similar question but with javascript here. Accepted answer

const data = [
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' }, 
  { group: 'A', name: 'MM' },
  { group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']

However if you try the same thing with typescript you get an error ts2802 Type 'Set' can only be iterated through when using the '--downlevelIteration' flag or with a '--target' of 'es2015' or higher

How can you achieve the same results with typescript?

Question two How about you want to get unique objects rather than strings . For eample if you want to get

[
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' },
] 

CodePudding user response:

This should solve your issue:

const array = Array.from(new Set(data.map(item => item.group)));

Note: Spreading a Set has issues when compiled with TypeScript. It's safer to use Array.from above instead.

CodePudding user response:

Just use compilation target in your tsconfig.json as ES6 or higher:

"compilerOptions": {
  "target": "ES6"
}

Your current target must be ancient, hence the error.

Other than that, your original code is perfectly correct.

  • Related