从javascript对象访问特定键

时间:2018-02-16 07:59:20

标签: javascript

我用过这个: -

var user = result.user;
alert(JSON.stringify(user));

以上代码已返回此数据

{
  "uid": "Kbkd6QMsqIhJ4pe3QXyEUjoAohN2",
  "displayName": "Prince Hamza",
  "photoURL": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg",
  "email": "princehamzi.mine@gmail.com",
  "emailVerified": true,
  "phoneNumber": null,
  "isAnonymous": false,
  "providerData": [
    {
      "uid": "110862942226973616842",
      "displayName": "Prince Hamza",
      "photoURL": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg",
      "email": "princehamzi.mine@gmail.com",
      "phoneNumber": null,
      "providerId": "google.com"
    }
  ]
}

但我无法专门阅读此数据 我希望它返回uid,photoURL,姓名,电子邮件;:特别是

2 个答案:

答案 0 :(得分:2)

您可以使用object destructuring之类的

      const data = {"uid":"Kbkd6QMsqIhJ4pe3QXyEUjoAohN2","displayName":"Prince Hamza","photoURL":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg","email":"princehamzi.mine@gmail.com","emailVerified":true,"phoneNumber":null,"isAnonymous":false,"providerData":[{"uid":"110862942226973616842","displayName":"Prince Hamza","photoURL":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg","email":"princehamzi.mine@gmail.com","phoneNumber":null,"providerId":"google.com"}] }

    const {uid , photoURL , name , email} = data;

    console.log({ uid, photoURL, name, email});

答案 1 :(得分:0)

只需返回包含所需元素的对象即可。你不需要做任何特别的事情。如下所示:

return {
     "uuid": user.uid,
     "photoURL": user.photoURL,
     "displayName": user.displayName
     ....etc
}