2012-08-24 23 views
2

實際上,問題與typeahead引導 有關,因爲我需要使用自動完成來定義要在輸入文本中顯示的值數組。過濾一組對象以獲得數組值

無論如何,目標只是定義一個讀取對象數組並返回一個字符串數組的函數。 這是我的代碼(1)。

(1)的目標是: 1)從對象數組中獲取字符串數組。 2)過濾這個數組,拒絕一些元素。

它不起作用,因爲我想拒絕的元素在數組中繼續存在。 事實上,在自動完成中,我得到了錯誤的值,實際上它破壞了代碼,因爲錯誤並不是預期的。

應該如何修復代碼並改進它?


(1)

element.typeahead({ 
    source: function ({ 
     var users = _.map(app.userCollection.models, function (model) { 
      if (model.get('id') === app.currentUser.id) { 
       return false; 
      } 
      return model.get('first_name') + ' ' + model.get('last_name'); 
     }); 
     console.log(users); // [false, 'some name']; 
     _.reject(users, function(name) { 
      return name === false; 
     }); 
     console.log(users); // [false, 'some name']; 
          // why does the false value persist? 
     return users; 
    } 
}); 

回答

4

下劃線方法通常不會在陣列本身上運行,但它們返回一個新的數組,但我建議逐一檢查每一個功能下劃線docs確認。在這種情況下,我們可以有把握地認爲拒絕退貨一些新的陣列,根據這句話在下劃線docs

返回列表中的值沒有,說實話測試(迭代器)傳遞的元素。

什麼目前你正在做的是:

_.reject(users, function(name) { 
    return name === false; 
}); 

所以,你實際上並沒有保存結果的任何地方。爲了保持對數組的引用沒有不需要的元素做到這一點:

users = _.reject(users, function(name) { 
    return name === false; 
}); 

這將產生你想要的結果,但讓我給你一個重構提示:

使用骨幹自己的方法,只要你可以,它會使更多的可讀代碼

source: function() { 
    // filter the collection down to the users you want 
    var users = app.userCollection.filter(function(model) { 
    return model.id === app.currentUser.id; 
    }); 
    // -> users is now an array of models 

    // use map to transform each wanted user to a string giving its full name 
    users = _.map(users, function(user) { 
    return user.get('first_name')+' '+user.get('last_name'); 
    }); 
    // -> users is now an array of strings 

    return users; 
} 

希望這有助於!

+0

它有幫助,除了我想獲得模型'model.id!== app.currentUser.id;'而不是'model.id === app.currentUser.id;'。非常感謝。 –

+0

好吧,一個小技巧,你明白了 – jakee