2013-03-30 24 views
1

我正在使用underscoreJS來管理摔跤手對象的列表,他們有一個錦標賽對象附加了細節或設置爲false。下劃線JS groupBy:更好的字段名稱

請看看這個代碼片段:http://jsfiddle.net/JpPjA/

var wrestlers = [{"id":60,"alias":"Natalya Hart","male":true,"championship":false,"alias_url":"natalya-hart"},{"id":59,"alias":"Naomi","male":true,"championship":false,"alias_url":"naomi"},{"id":58,"alias":"Layla","male":true,"championship":false,"alias_url":"layla"},{"id":4,"alias":"The Rock","male":true,"championship":{"id":3,"image":"wwe-championship.png","title":"WWE Championship"},"alias_url":"the-rock"}, 
{"id":3,"alias":"Antonio Cesaro","male":true,"championship":{"id":5,"image":"wwe-united-states-championship.png","title":"WWE United States Championship"},"alias_url":"antonio-cesaro"},{"id":2,"alias":"Wade Barrett","male":true,"championship":{"id":4,"image":"wwe-intercontinental-championship.png","title":"WWE Intercontinental Championship"},"alias_url":"wade-barrett"}, 
{"id":1,"alias":"Alberto Del Rio","male":true,"championship":{"id":2,"image":"world-heavyweight-championship.png","title":"World Heavyweight Championship"},"alias_url":"alberto-del-rio"}]; 

var g = _.groupBy(wrestlers, 'championship'); 

console.log(JSON.stringify(g)); 

不幸的是將其作爲兩個鍵名的數組:「假」和「的翻譯:」

是否有提供輸出預定義鍵名的方法? [對象對象]作爲關鍵名稱困擾我更多。

+0

一撥弄*雙向*示例和摔跤手:http://jsfiddle.net/userdude/JpPjA/24/ –

回答

2

你可以通過一個函數來完成你的測試和應用自定義標籤:

var g = _.groupBy(wrestlers, function champs(o) { 
    return o.championship === false ? 'notchamps' : 'champs'; 
}); 

http://jsfiddle.net/userdude/JpPjA/25/

也許有一點更有趣......

var g = _.groupBy(wrestlers, function has(a) { 
    return a.championship !== false ? 'champs' : 'chumps'; 
}); 
+0

謝謝----- – azz0r

+0

嘿,沒問題。 –