-1

I have an array of object as shown below:

[{
    "name": "Okta Verify Push",
    "provider": "OKTA",
    "type": "push",
    "status": 0,
    "id": "opfhgfgaidhyBw2H90h7"
}, {
    "name": "Okta Verify TOTP",
    "provider": "OKTA",
    "type": "token:software:totp",
    "status": 0,
    "id": "osthgek5jmWTckcka0h7"
}, {
    "name": "Unknown",
    "provider": "CUSTOM",
    "type": "claims_provider",
    "status": 1,
    "id": "clpn4wdtqtH6geILD0h7"
}, {
    "name": "Google Authenticator",
    "provider": "GOOGLE",
    "type": "token:software:totp",
    "status": 1,
    "id": null
}]

I want to get the distinct object as array based on the **provider**

I tried

[...new Set(item.filter(factor => factor.status == MultiFactorAuthenticationEnrolmentStatus.Enrolled).map(factor => factor.provider))];

This returns string of array such as ["GOOGLE", "OKTA","CUSTOM"]

My requirement is to get the Array of Object such as

[{
    "name": "Okta Verify Push",
    "provider": "OKTA",
    "type": "push",
    "status": 0,
    "id": "opfhgfgaidhyBw2H90h7"
},  {
    "name": "Unknown",
    "provider": "CUSTOM",
    "type": "claims_provider",
    "status": 1,
    "id": "clpn4wdtqtH6geILD0h7"
}, {
    "name": "Google Authenticator",
    "provider": "GOOGLE",
    "type": "token:software:totp",
    "status": 1,
    "id": null
}]

Reference - How to get distinct values from an array of objects in JavaScript?

San Jaisy
  • 15,327
  • 34
  • 171
  • 290

1 Answers1

3

In the case that you have a preference for taking the first occurrence, you can first map the data into an object based on provider being the key and itself as the value. Once that is done, you can then extract the all of the values with Object#values.

const data = [{
    "name": "Okta Verify Push",
    "provider": "OKTA",
    "type": "push",
    "status": 0,
    "id": "opfhgfgaidhyBw2H90h7"
}, {
    "name": "Okta Verify TOTP",
    "provider": "OKTA",
    "type": "token:software:totp",
    "status": 0,
    "id": "osthgek5jmWTckcka0h7"
}, {
    "name": "Unknown",
    "provider": "CUSTOM",
    "type": "claims_provider",
    "status": 1,
    "id": "clpn4wdtqtH6geILD0h7"
}, {
    "name": "Google Authenticator",
    "provider": "GOOGLE",
    "type": "token:software:totp",
    "status": 1,
    "id": null
}]


const values = Object.values(
  data.reduce((a, b) => {
    if (!a[b.provider]) a[b.provider] = b 
      return a
   }, {})
)

console.log(values)
woat
  • 431
  • 3
  • 8