h bob
h bob

Reputation: 3780

Use Underscore to transform/wrap an entire object into a new object

Underscore has mapping for arrays and functions, but they work on the individual items, not the entire thing.

So suppose I want to change an object's "shape" while chaining:

var result = _.chain(foo)
  .pluck(...)
  .stuff()
  .moreStuff()
  .TRANSFORMHERE()     // <------ what step/steps here to wrap the object? 
  .evenMoreStuff()
  .value();

So something like:

{ a: 1, b: 2, c: 3, d: 4} 

to

{ foo: {a: 1, b: 2, c: 3, d: 4}, bar: "hello" }

Without chaining it's easy. But what steps can I take while chaining, to take an object and wrap it as a property within a new object?

Upvotes: 0

Views: 95

Answers (2)

h bob
h bob

Reputation: 3780

Unless someone has a better/easier/builtin way, I guess we can add a function to underscore:

_.mixin({
  wrapObject: function(obj, name) {
    var outer = {};
    outer[name] = obj;
    return outer;
  }
});

Upvotes: 0

Magus
Magus

Reputation: 15104

You want to use tap.

var result = _.chain(foo)
  .pluck(...)
  .stuff()
  .moreStuff()
  .tap(function(obj) {
      obj.foo = { a : obj.a, b : obj.b, c : obj.c, d : obj.d };
      obj.bar = "hello";

      // Delete old keys
      delete obj.a;
      delete obj.b;
      delete obj.c;
      delete obj.d;
  })
  .evenMoreStuff()
  .value();

Not that you can't do something like this :

tap(function(obj) {
    return {
        a : obj.a,
        ...
        bar : "hello"
    };
});

The result of tap is ignored by underscore. So you have to modify the object directly.

Upvotes: 1

Related Questions