输入:
var animals = [
{category: "mammal", name: "dog", categoryID: "MAM"},
{category: "fish", name: "pickerel", categoryID: "FIS"},
{category: "mammal", name: "cat", categoryID: "MAM"},
{category: "mammal", name: "monkey", categoryID: "MAM"},
{category: "bird", name: "budgie", categoryID: "BIRD"}
];
期望的输出:
var categories = [
{name: "mammal", catId: "MAM"},
{name: "bird", catId: "BIR"},
{name: "fish", catId: "FIS"}
];
使用下划线有一个很好的方法吗?
我最接近的是jsFiddle:
var categories = _.groupBy(animals, function(animal) {
return animal.category;
});
使用此输出:
Object {mammal: Array[3], fish: Array[1], bird: Array[1]}
但有没有办法以一种很好的方式返回上面所需的输出?
答案 0 :(得分:1)
您可以使用reduce
代替groupBy
以便捷的格式收集您的姓名和身份证件:
var collect_categories = function(o, e) {
o[e.categoryID] = e.category;
return o;
};
var o = _(animals).reduce(collect_categories, { })
然后使用map
将该对象解压缩到一个对象数组中:
var unpack = function(name, id) {
return { name: name, catID: id };
};
var a = _(o).map(unpack);
当您将这些函数与chain
组合时,帮助函数更有意义:
var categories = _(animals).chain()
.reduce(collect_categories, { })
.map(unpack)
.value();
我发现命名函数会使代码比匿名函数更简洁,名称有助于表示代码的意图。