Google API 3联系人,将字符串数组转换为键值对

时间:2017-08-23 02:08:40

标签: jquery arrays json ajax google-contacts

我尝试转换从Google API联系人检索到的电子邮件

基本上我只想转换此电子邮件数组

["pragya.bajracharya@longtailux.com.au",
"support+id34845@autopilothq.zendesk.com",
"john.concepcion@microsourcing.com",
"reinagonzales@sharpmindscontent.com"]

进入此

{email: 'nikola@tesla.com'},
{email: 'brian@thirdroute.com'},
{email: 'gilbert@spacer.com'},
{email: 'someone@gmail.com'}

下面是我使用的代码,如何从谷歌联系人中检索电子邮件



function auth() {
	    var config = {
	      'client_id': 'MY_CLIENT_ID'
	    };
	    gapi.auth.authorize(config, function() {
	      fetch(gapi.auth.getToken());  
	     
	    });
	  }
	
	  var fetch =function fetch(token) {
	    $.ajax({
		    url:"https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=10000&access_token=" + token.access_token,
		    dataType: "jsonp",
		    success:function(data) {
          // display all your data in console   
          var emailAddresses = JSON.stringify(data.feed.entry.map(function(entry) {
              //take the first gd$email item the entry has
              var gdEmail =   entry['gd$email'][0];
              //this assumes all entries will have a gd$email, 
              var emails =  gdEmail.address;
              return emails;
          }));
         console.log(emailAddresses);
		    }
		});
	}	

<button onclick="auth();">GET CONTACTS FEED</button>
&#13;
&#13;
&#13;

这是来自console.log(emailAddresses);

的示例结果
["pragya.bajracharya@longtailux.com.au",
"support+id34845@autopilothq.zendesk.com",
"john.concepcion@microsourcing.com",
"reinagonzales@sharpmindscontent.com"]

1 个答案:

答案 0 :(得分:1)

var emailaddress = ["pragya.bajracharya@longtailux.com.au",
  "support+id34845@autopilothq.zendesk.com",
  "john.concepcion@microsourcing.com",
  "reinagonzales@sharpmindscontent.com"
];

console.log(emailaddress);

var newarr = [];
// Loop through all email address and push to new array with your key
emailaddress.forEach(function(val, index) {
  newarr.push({
    "email": val
  })
});

console.log(newarr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

修改

你是一个串行的数组,所以它不起作用。

使用以下代码

 var emailAddresses = data.feed.entry.map(function(entry) {
      //take the first gd$email item the entry has
      var gdEmail =   entry['gd$email'][0];
      //this assumes all entries will have a gd$email, 
      var emails =  gdEmail.address;
      return emails;
});