2

I am trying to convert the following dataset:

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" }
           ]
       }

into something like this:

var foo1 = {
        "2011":
            [{ "y": "1400" }],
        "2012": 
            [{ "y": "730" }]
       }

What would be the best way to do this using UnderscoreJS? Thanks in advance!

4
  • Why do you want to reduce to an array? Commented May 28, 2014 at 12:18
  • Why would you want to do that? Commented May 28, 2014 at 12:20
  • Trying to render several reports client-side in a dashboard and need to be able to modify the dataset without having to make repeated server calls for each report. Commented May 28, 2014 at 12:22
  • Why are those numbers strings? Commented May 28, 2014 at 12:28

1 Answer 1

1

Underscore does not have a utility for object mapping unfortunately. We'd have to emulate that with _.object(_.keys(…), _.map(_.values(…), …)) or by _.cloneing the object, iterating it by _.each and manually assigning. Let's better extend the lib to get more readable code:

_.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) }];
});
Sign up to request clarification or add additional context in comments.

3 Comments

Just what the OP wanted: a map and a reduce (though not a map-reduce). Better now with the helper function?
I was trying to make a joke, but no, it's still to me, totally unreadable but it works and feels overly complicated just because it's underscore, but correct nonetheless.
Please, come up with an easier solution, I'd appreciate it :-) I've further simplified it, now using an actual map-reduce. More readable now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.