2013-10-28 48 views
-4

我有個同學組成的數組(所有的ID是唯一的):查找名稱jQuery的陣列ID

[Object {ID: 1, "John"}, Object {ID: 2, "Joseph"} ] 

我有一個字符串的另一個數組["John","Ram"](我們稱之爲「陣列2」)。 如何在數組2中找到名稱存在的學生的ID(不考慮大小寫,即不區分大小寫)?

+0

如若 '字符串的其他陣' 是'[ 「約翰」, 「公羊」]'? – George

+3

'{ID:1,「John」}'不是一個合適的對象 - 這些名字應該在一個屬性中設置。 – guessimtoolate

+0

我編輯爲Object {ID:1,「John」} –

回答

1

編輯:刪除jQuery並修復大小寫敏感問題。請注意,由於在Array.prototype上使用了map()forEach()indexOf(),因此這是no longer compatible with IE8

沿着這些路線的東西會做的伎倆:

var names = ['John', 'Joe', 'Ralph'], 
    data = [ 
     { 
      id: 1, 
      name: 'John' 
     }, 
     { 
      id: 2, 
      name: 'Joseph' 
     }, 
     { 
      id: 3, 
      name: 'ralph' 
     } 
    ], 
    results = []; 

var lnames = names.map(function(name) { 
    return name.toLowerCase(); 
}); 

data.forEach(function(item) { 
    if (lnames.indexOf(item.name.toLowerCase()) > -1) { 
     results.push(item.id); 
    } 
}); 

console.log('found: ', results); 

這裏是一個活生生的例子:http://jsfiddle.net/6ptz3/2/

+0

這裏是一個原生的JS解決方案btw - 哪個_still_不回答OP的問題,因爲問題沒有很好地形成,並且結構不清晰:'var ids = studentsArray.filter(function(elem){namespaceArray。 indexOf(elem.name)!== -1;/*在名稱數組*/ })。map(function(elem){ return elem.ID; });' –

+0

在編輯最後一句之前在讀的問題:「[我正在使用jquery]」...所以,回答你的問題:OP。 – tiffon

+0

然後道歉,我的不好。我沒有看到OP提到他在編輯之前使用jQuery。 –