【问题标题】:cognito user attributes to plain object认知用户属性到普通对象
【发布时间】:2021-08-14 06:52:58
【问题描述】:

我正在尝试将从 CognitoIdentityServiceProvider listUsersInGroup 获得的 Cognito 用户属性转换为普通对象,但我没有找到任何库或 AWS 函数可以做到这一点......然后我尝试自己实现它

这就是我想出的:

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

但这会创建一个包含对象的数组,我正在尝试创建一个包含所有属性的对象...

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

这是用户数据的示例(属性可能因用户而异):

用户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",
    }
]

用户 b:

[
    {
        "Name": "custom:age",
        "Value": "0",
    },
    {
        "Name": "custom:height",
        "Value": "0",
    },
    {
        "Name": "email",
        "Value": "dsafdsa@gmail.com",
    }
]

【问题讨论】:

    标签: javascript amazon-cognito


    【解决方案1】:

    使用循环看起来很简单。仅供参考:数组的映射函数总是返回数组

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

    【讨论】:

      【解决方案2】:

      你可以使用reduce

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

      【讨论】:

        猜你喜欢
        • 2016-02-17
        • 2014-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-08
        • 1970-01-01
        相关资源
        最近更新 更多