2

I have inherited an express application. In the application we pass to res.render a massive list of local variables. For every page we pass about 30 variables that do not change. If one does change it needs to be changed in a dozen places. This is obviously bad.

So what I want to do store the values locals that do not change separate from the truly local. So I placed these non-changing values in their own file and load the file at the start of each route, like so:

'use strict';
var locals = 
{
    indexName: 'Home',
    ...lots more of these...
};
module.exports = { locals : locals };


// in each route files
var local = require('../locals.js');

And I can use it via res.render('sensor', local.locals);

However I also need to add page specific values. So I tried local.locals + { ... }; which doesn't while it doesn't give an error doesn't even show the original values.

I then tried local.locals.concat({...}) but that does give an error (TypeError: Object #<Object> has no method 'concat'), likewise for extend and push.

Is there no methods to extend or merge two objects? Do I need to roll my own?

Also, is this the best way of making the an array global? I would prefer just to call it locals, and not local.locals as that is just cumbersome.

graham.reeds
  • 16,230
  • 17
  • 74
  • 137
  • I get `TypeError: Object # has no method 'assign'` for that too. – graham.reeds Apr 15 '16 at 07:01
  • After looking at the `Object.assign` documentation I changed the parameters and now I get `TypeError: Object function Object() { [native code] } has no method 'assign'`. I will look at lodash. – graham.reeds Apr 15 '16 at 07:49
  • `Object.assign` is a static member function but you are trying to use it as instance member function. I don't get why you don't google it properly. This is not rocket science if you have a C++ background. – mostruash Apr 15 '16 at 09:44

1 Answers1

2

In addition to Object.assign from @mostruash, there are two JS libraries that are very similar, which both provide an object merge function (along with a lot of nice helper utilities). Pick one:

Edit: and as to your second question about local.locals...of course, just export the object itself, rather than an object that wraps it:

module.exports = locals;

...and in your routes:

var locals = require('../locals');
console.log(locals.indexName);
user2926055
  • 1,963
  • 11
  • 10