Javascript filter array -
why following function return undefined when executed? seems though filter function indeed return appropriate object i'm not seeing why can't passed callback function. i'm new js.
function getuserbyid(usersarr, userid, cb){ cb((usersarr.filter(function(el){ return el.id === userid; })[0])); } getuserbyid(users, '15a', function(user){ return 'the user id 15a has email of ' + user.email + ' name of ' + user.name + ' , address of ' + user.address; }); var users = [ { id: '43d', email: 'james@gmail.com', name: 'james', address: '16 n' }, { id: '15a', email: 'carry@gmail.com', name: 'carry', address: '14 n' }, { id: '87t', email: 'jeff@gmail.com', name: 'jeff', address: '23 n' }, ];
if have array of objects, , 1 or more of objects have id property assigned '15a', filter should work.
here's example:
function getuserbyid(usersarr, userid, cb) { cb(usersarr.filter(function (el) { return el.id === userid; })[0]); } var users = [{ id: '15a', name: 'bob', email: 'bob@example.com', address: '123 main street' }, { id: 'zxv', name: 'jim', email: 'jim@example.com', address: '234 main ave' }]; getuserbyid(users, '15a', function (user) { document.getelementbyid('output').innerhtml = 'the user id 15a has email of ' + user.email + ' name of ' + user.name + ' , address of ' + user.address; });
jsfiddle: https://jsfiddle.net/0skhn9k9/2/
edit: make example work need return value of callback
function getuserbyid(usersarr, userid, cb){ return cb((usersarr.filter(function(el){ return el.id === userid; })[0])); } getuserbyid(users, '15a', function(user){ return 'the user id 15a has email of ' + user.email + ' name of ' + user.name + ' , address of ' + user.address; }); var users = [ { id: '43d', email: 'james@gmail.com', name: 'james', address: '16 n' }, { id: '15a', email: 'carry@gmail.com', name: 'carry', address: '14 n' }, { id: '87t', email: 'jeff@gmail.com', name: 'jeff', address: '23 n' }, ];
Comments
Post a Comment