如何遍历由对象组成的数组并回调特定对象值?的JavaScript /回调

时间:2016-02-11 21:41:17

标签: javascript callback for-in-loop

我是JavaScript的新手。我只做了不到一个月,所以请原谅我......

我给了一个由3个不同对象组成的数组。我需要这样做,以便底部的console.log将按预期返回。即,当数组'users'通过for循环时,它将搜索字符串值'16t',并找到具有该值的对象,并正确显示信息

这是我到目前为止所做的:

var users = function(arr, callback) {
 for( var i = 0; i < arr.length; i++ ) {
    var obj = arr[ i ];
    for (var prop in obj) {
        if(obj.hasOwnProperty(prop) === '16t'){
            callback(obj[prop]);
        }
    }
  }
 };

这是问题所在:

var users = [
  {
    id: '12d',
    email: 'tyler@gmail.com',
    name: 'Tyler',
    address: '167 East 500 North'
  },
  {
    id: '15a',
    email: 'cahlan@gmail.com',
    name: 'Cahlan',
    address: '135 East 320 North'
  },
  {
    id: '16t',
    email: 'ryan@gmail.com',
    name: 'Ryan',
    address: '192 East 32 North'
  },
];

getUserById(users, '16t', function(user){
    console.log('The user with the id 16t has the email of ' + user.email + ' the name of ' + user.name + ' and the address of ' + user.address);
});

1 个答案:

答案 0 :(得分:1)

只为该用户过滤:

function getUserById(users, id, callback) {
  return callback(users.filter(function(user) {
    return user.id === id;
  })[0]);
}

getUserById(users, '16t', function(user){
  console.log('The user with the id ' + user.id + ' has the email of ' + user.email + ' the name of ' + user.name + ' and the address of ' + user.address);
});

修改

lodash _.find也为您做到了这一点:

function getUserById(users, id, callback) {
  return callback(_.find(users, function(user) {
    return user.id === id;
  }));
}

您可以在line 7,570上查看其源代码,了解它们如何处理优化。