gpt4 book ai didi

javascript - underscoreJS groupBy : better field names

转载 作者:行者123 更新时间:2023-11-30 18:06:22 25 4
gpt4 key购买 nike

我正在使用 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] 作为键名更让我困扰。

最佳答案

您可以传递一个函数来进行测试并应用自定义标签:

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';
});

关于javascript - underscoreJS groupBy : better field names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15718156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com