Sush
Sush

Reputation: 1457

Return a value from json data if two values are equal

function getusername(userid) {
  $.get('/getRecentSignups', function (data) {

console.log(JSON.stringify(data);

//prints
{"_id":"5306e7fd80b1027ad2653db4","email":"[email protected]","id":"27","password":"priya","signedtime":"2014-02-21 11:15:33"},{"_id":"5306e81880b1027ad2653db5","email":"[email protected]","id":"35","password":"anju","signedtime":"2014-02-21 11:16:00"}]

// userid passing here is 35

    data = data.filter(function(val) {
       return (val.id === userid)
         });
  });
}

In the above function getusername() I am passing userid 35

Data prints //prints

    {
  "_id": "5306e7fd80b1027ad2653db4",
  "email": "[email protected]",
  "id": "27",
  "password": "priya",
  "signedtime": "2014-02-21 11:15:33"
},
{
  "_id": "5306e81880b1027ad2653db5",
  "email": "[email protected]",
  "id": "35",
  "password": "anju",
  "signedtime": "2014-02-21 11:16:00"
}]

I have to return corresponding email when userid equals data.id how it is possible?

Upvotes: 0

Views: 176

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

First, you can't return a value from the method as it is asynchronous, you need to use a callback pattern to solve this like

function getusername(userid, callback) {
    $.get('/getRecentSignups', function (data) {
        data = data.filter(function (val) {
            return (val.id == userid)
        });
        if (data && data.length) {
            callback(data[0].email);
        } else {
            callback(userid);
        }
    });
}
getusername(35, function (email) {
    //do something
})

See How to return the response from an AJAX call?

Upvotes: 1

Related Questions