Chris Browne
Chris Browne

Reputation: 1612

Node.js adding multiple properties to an object

I'm wondering if there's a better way of doing this:

module.exports.foo = "bar";
module.exports.bar = "baz";
module.exports.foobar = "foobaz";

Now, I've heard about 'with' (and its dangers) but it doesn't work here because it can't add new properties to an object, it can only change existing properties. In fact if you try to add new properties you end up clobbering the enclosing scope which isn't very nice.

Something like this would be nice:

module.exports += {
  foo: "bar",
  bar: "baz",
  foobar: "foobaz"
}

But that converts both sides to strings before concatenating them which is not what I want.

Does such syntactic sugar exist in Node.JS-flavoured JavaScript? Maybe a function on 'module' to add lots of properties at once?

Upvotes: 3

Views: 2536

Answers (3)

user3276332
user3276332

Reputation: 11

Use Object.assign()

Object.assign(module.exports, {
              foo: "bar",
              bar: "baz",
              foobar: "foobaz"
            });

Upvotes: 1

bguiz
bguiz

Reputation: 28587

Consider using _.extend

So in your example:

            module.exports += {
              foo: "bar",
              bar: "baz",
              foobar: "foobaz"
            }

Would be:

            var _ = require('underscore');

            _.extend(module.exports,
                {
                  foo: "bar",
                  bar: "baz",
                  foobar: "foobaz"
                }
            );

Or, if you do not want any dependencies, using raw javascript:

            function myExtend(dest, obj) {
                for (key in obj) {
                    var val = obj[key];
                    dest[key] = val;
                }
            }
            myExtend(module.exports,
                {
                  foo: "bar",
                  bar: "baz",
                  foobar: "foobaz"
                }
            );

If you are using the latter method, make sure to check for edge cases, which I haven't here!

Upvotes: 0

Rob
Rob

Reputation: 12872

You could write a simple function to loop over them and add them to module.exports or you can try node.extend which tries to mimic jquery's $.extend()

Upvotes: 3

Related Questions