1

I am using underscoreJS to manage a list of wrestler objects, they have a championship object attached that has details or is set to false.

Please take a look at this code snippet: 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));

Unfortunately it outputs it as an array with two key names: "false" and "[object Object]"

Is there a way to give the output predefined key names? [object Object] as a key name bothers me more.

4

1 回答 1

2

You can pass a function to do your test and apply custom labels:

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

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

Maybe a little more fun...

var g = _.groupBy(wrestlers, function has(a) {
    return a.championship !== false ? 'champs' : 'chumps';
});
于 2013-03-30T11:56:57.920 回答