我正在尝试转换以下数据集:
var foo = {
"2011":
[{ "date": "2011-08-01T00:00:00", "y": "100" },
{ "date": "2011-08-05T00:00:00", "y": "400" },
{ "date": "2011-09-01T00:00:00", "y": "900" }
],
"2012":
[{ "date": "2012-07-22T00:00:00", "y": "200" },
{ "date": "2012-09-22T00:00:00", "y": "430" },
{ "date": "2012-10-26T00:00:00", "y": "100" }
]
}
这样的事情:
var foo1 = {
"2011":
[{ "y": "1400" }],
"2012":
[{ "y": "730" }]
}
使用UnderscoreJS最好的方法是什么?提前谢谢!
答案 0 :(得分:1)
不幸的是,Underscore没有用于对象映射的实用程序。我们必须使用_.object(_.keys(…), _.map(_.values(…), …))
或_.clone
对象进行模拟,然后按_.each
进行迭代并手动分配。让我们更好地扩展lib以获得更易读的代码:
_.mixin({
mapObject: function(obj, iterator, context) {
return _.each(_.clone(obj), function(items, p, o) {
o[p] = iterator.apply(this, arguments);
}, context);
}
});
var foo1 = _.mapObject(foo, function(items) {
return [{y: _.reduce(_.map(_.pluck(items, "y"), Number), function(m, y) {
return m + y;
}, 0) }];
});