ronara
ronara

Reputation: 366

cognito user attributes to plain object

I'm trying to convert the Cognito user attributes I get from CognitoIdentityServiceProvider listUsersInGroup to plain object but I didn't found any library or AWS function that does it... then I tried to implement it by myself

That's what I came up with:

{
    ...user,
    Attributes: user.Attributes.map((x) => ({ [x.Name]: x.Value })),
}

But that makes an array with objects and I'm trying to create an object with all the attributes...

[
    {
        "sub": "dasfdasfd-vcfdgfd",
    },
    {
        "website": "aba",
    },
    {
        "address": "new",
    },
]

here is an example of the user's data (the attributes can be different from user to user):

user a:

[
    {
        "Name": "sub",
        "Value": "dasfdasfd-vcfdgfd",
    },
    {
        "Name": "website",
        "Value": "aba",
    },
    {
        "Name": "address",
        "Value": "new",
    },
    {
        "Name": "email_verified",
        "Value": "false",
    },
    {
        "Name": "phone_number_verified",
        "Value": "false",
    }
]

user b:

[
    {
        "Name": "custom:age",
        "Value": "0",
    },
    {
        "Name": "custom:height",
        "Value": "0",
    },
    {
        "Name": "email",
        "Value": "[email protected]",
    }
]

Upvotes: 1

Views: 1062

Answers (2)

Andrew Gillis
Andrew Gillis

Reputation: 3885

You can use reduce

{
    ...user,
    Attributes: user.Attributes.reduce((acc, { Name, Value }) => ({...acc, [Name]: Value }), {}),
}

Upvotes: 4

Root
Root

Reputation: 132

Seems pretty simple just use loop. FYI : Array's map function always returns the array

function getAttributes(data){
 let attributes = {};
 for(let x of data){
    attributes[x["name"]] = x["value"];
 }
 return attributes;
}

{
    ...user,
    Attributes: getAttributes(user.Attributes)
}

Upvotes: 0

Related Questions