I am using the AWS Cognito listUsers API to get a list of all my users from my Cognito pool. I have successfully managed to return the array of users but I'm now stuck on how to transform that array into a flattened array. Here is an example of the data I receive from the AWS listUsers API:
[
{
Username: "xx001",
Attributes: [
{
Name: "given_name",
Value: "Jeff"
},
{
Name: "family_name",
Value: "Smith"
},
{
Name: "email",
Value: "[email protected]"
}
],
UserStatus: "Confirmed",
},
{
Username: "yy002",
Attributes: [
{
Name: "given_name",
Value: "Steve"
},
{
Name: "family_name",
Value: "Jones"
},
{
Name: "email",
Value: "[email protected]"
}
],
UserStatus: "Confirmed",
}
]
I would like to transform the above array into the following structure:
[
{
Username: "xx001",
given_name: "Jeff",
family_name: "Smith",
email: "[email protected]",
UserStatus: "Confirmed"
},
{
Username: "yy002",
given_name: "Steve",
family_name: "Jones",
email: "[email protected]"
UserStatus: "Confirmed"
}
]
If anyone could point me in the right direction it would be greatly appreciated!
you can use map
to transform the array
const users = [ { Username: "xx001", Attributes: [ { Name: "given_name", Value: "Jeff" }, { Name: "family_name", Value: "Smith" }, { Name: "email", Value: "[email protected]" } ], UserStatus: "Confirmed", }, { Username: "yy002", Attributes: [ { Name: "given_name", Value: "Steve" }, { Name: "family_name", Value: "Jones" }, { Name: "email", Value: "[email protected]" } ], UserStatus: "Confirmed", } ]
const res = users.map(({Attributes,...rest}) => {
const attrObj = Attributes.reduce((acc,{Name,Value}) => ({...acc, [Name]:Value}),{})
return {...rest,...attrObj }
})
console.log(res)
if the attributes are fixed and not dynamic you don't even have to use reduce
and spread. Therefore this will be faster than the first.
const users = [ { Username: "xx001", Attributes: [ { Name: "given_name", Value: "Jeff" }, { Name: "family_name", Value: "Smith" }, { Name: "email", Value: "[email protected]" } ], UserStatus: "Confirmed", }, { Username: "yy002", Attributes: [ { Name: "given_name", Value: "Steve" }, { Name: "family_name", Value: "Jones" }, { Name: "email", Value: "[email protected]" } ], UserStatus: "Confirmed", } ]
const res = users.map(({Attributes,Username,UserStatus}) => {
return {Username,UserStatus, [Attributes[0]["Name"]]:Attributes[0]["Value"],[Attributes[1]["Name"]]:Attributes[1]["Value"],[Attributes[2]["Name"]]:Attributes[2]["Value"]}
})
console.log(res)