underscoreJS groupBy:更好的字段名称

时间:2013-03-30 11:44:22

标签: javascript underscore.js

我使用underscoreJS来管理摔跤手对象列表,他们附加了一个冠军对象,其中包含详细信息或设置为false。

请查看以下代码段: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));

不幸的是,它将它输出为具有两个键名的数组:“false”和“[object Object]”

有没有办法给输出预定义的键名? [object Object]作为一个关键名称让我更加困扰。

1 个答案:

答案 0 :(得分: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';
});