Combining two JSON objects within the server environment

Managing a large list of local variables in an inherited express application can be tricky. Passing around 30 unchanging variables to res.render for every page is not ideal, especially when changes need to be made in multiple locations.

To address this issue, I decided to separate the static values from the dynamic ones. I created a separate file for the non-changing values and load it at the beginning of each route:

'use strict';
var locals = 
{
    indexName: 'Home',
    ...many more values...
};
module.exports = { locals : locals };


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

This allows me to use these global values with

res.render('sensor', local.locals);

However, adding page-specific values proved to be challenging. Attempting local.locals + {...}; did not work as expected, nor did local.locals.concat({...}), resulting in errors like

TypeError: Object #<Object> has no method 'concat'
.

Are there any methods available to merge two objects seamlessly? Or do I need to create my own solution?

Furthermore, is this approach the most efficient way to handle global arrays? It might be better to simply call it locals instead of local.locals for easier access and readability.

Answer №1

Furthermore, alongside the suggestion by @mostruash regarding Object.assign, there are a couple of JS frameworks that share similarities and offer object merging capabilities, in addition to other convenient helper functions. Take your pick from:

Edit: Also, addressing your second query about local.locals...simply export the object itself instead of wrapping it within another object:

module.exports = locals;

...and in your routes:

var locals = require('../locals');
console.log(locals.indexName);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Table sorting feature with checkboxes has disappeared from view

This segment of code includes HTML for a table along with JavaScript functionality. When a checkbox is clicked, another table will be displayed: <form class="filter"> <input type="checkbox" id="checkboxID" class="unchecked"> EG <input type= ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...

My goal is to retrieve and print the duplicated values only once from an associative array

Given an associative array, I need to print all the department names without any repetitions. <h3>2. List out all department names</h3> <div class="all"> </div> Here is my JavaScript code: var employee=[{"firstName":"Zahir","last ...

Introduce a pause using the raycaster function

When my raycaster intersects an object for 2 seconds, I want to update the object's texture. I attempted to use the clock function, but I am unsure of how to properly implement it. var clock = new THREE.Clock(); clock.autoStart = true; var inters ...

Error: Trying to access the parent node of an undefined property

After incorporating this script into my webpage for the newsletter sign-up process, I aimed to reveal customized content post user subscription. <script> function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode ...

The statement ""x=x || 4" will result in a `ReferenceError: x is not defined` because the

What is the reason behind receiving a ReferenceError: x is not defined error when using x = x || 4 or even x=(x||5), while var x = x || 4 operates as intended? ...

Issue with updating overall expenditure functionality

I'm currently in the process of developing a straightforward shopping cart with the help of simpleCart.js. Up until now, I've managed to successfully showcase items, add them to the basket, and proceed to checkout. However, my next challenge inv ...

"Looking to spice up your website with a dynamic background-image

I've encountered a problem with my CSS code for the header's background image. Despite trying various methods to create a slideshow, nothing seems to be working. Can someone provide guidance? I have four banner images named banner1, banner2, bann ...

Tips for transferring an image array by index from OneViewController to AnotherViewController on iOS?

As a newcomer to iOS Development, I recently created an application that utilizes JSON data. I successfully parsed this data into an array, which also contains another nested array. This nested array is also accessed by index in my code: if (responsedata. ...

attempting to access a variable which was initialized within a function in different sections of the code base

My goal is to retrieve a variable created within a function that is nested in a resize event parameter in jQuery. This variable should be dynamically updated each time the user resizes the browser window. I intend to utilize this variable to set the width ...

A guide on retrieving a JSON static file that has been imported using Webpack

I have a JSON static file named someFile.json within my project directory. This JSON file contains a stringified array of objects: [{...},{...},etc] To import it using Webpack (version 4.41.2), I use the following line in my App.js file: import '.. ...

Manipulating the DOM using a Flask route in an HTML form

I have a form that allows users to input the names of "Player A" and "Player B". When the user clicks on the "Start Game" button, the game begins by redirecting to a Flask route (/players). I want the "player-text" section to be updated with the player nam ...

You are unable to reference a member within the embed in discord.js v13

I created a system for logging join and leave events in my server. However, I encountered an issue where the member is not mentioned when the bot sends the embed in the channel. Here is a snippet of my code: client.on('guildMemberAdd', guildMemb ...

Attach the Bootstrap-Vue modal to the application's template

I am implementing a custom modal using bootstrap-vue modal in my project on codesandbox. This is the template structure: <template> <b-button variant="link" class="btn-remove" @click="removeItemFromOrder(index)"> Remove item </b-bu ...

Combining the results of JavaScript comparisons into a unified object array and adding a new value if it matches an existing value within the same

I am interested in consolidating the array to represent the base folder hierarchy. In the array provided, "Level 1" is the lowest level with no children folders. The "other level" contains various folders all under the "Top Level." The array structure is ...

Transferring information between different collections in MongoDB using Mongoose can lead to encountering a VersionError

I'm facing an issue where Mongoose is unable to find a matching document with the id when transferring data from one collection to another. On my website, users search for classes in a Mongo DB collection called "classes." Once they find a class succ ...

Reorganizing Elements within an Array using JavaScript

Imagine I have the characters: H, M, L I want to create sorted arrays like this: var array1 = [ "H", "M", "L", "L", "M", "H" ]; My goal is to avoid having more than one unique character in the first three and last three characters when using the shuffl ...

Utilizing the power of Material-UI with React in conjunction with Python-Django: A comprehensive

I am seeking guidance on implementing React with Material UI components in my web application. The technologies I have utilized in multiple projects include: Materialize CSS, Javascript, Jquery. The technologies I wish to explore for future projects are ...

JSON data does not display correctly after applying SerializeJSON function

When attempting to serialize the following data into JSON and checking the output, I am encountering a problem as demonstrated below: Line #13 : <cfset convertjson = SerializeJSON([ { ...

Combine the information from two dictionaries to create a single json object

I am attempting to convert two dictionaries into a JSON format consecutively using Python. I have created two dictionaries that appear as follows --- dictionary_quant = {'dmin': [0.003163, 14.325], 'magNst': [0.0, 414.0], 'horizon ...