The concept of immutability is crucial when utilizing a for-in loop to append an object to an array

Within my code, I have a nested loop structure consisting of a for of with a for in loop inside it. This setup retrieves information from a Neo4J database. By utilizing the Object.assign method, I am able to transfer a property from the fetched object into a new object. As far as I understand, this process ensures immutability.

In the subsequent step, I aim to incorporate the newly generated result object into an array for each returned result.

To achieve this, one option is to initialize an empty array outside the loop and then utilize Array.concat to create a fresh array during each iteration. However, I acknowledge that neither of these approaches truly maintain immutability since they involve either pushing elements into an array or overwriting a variable.

I am left wondering if there exists a method to culminate in an immutable results array containing all objects?

let results = []
for (const row of argsArray) {
    for (const key in row) {
        const neo4jPropInUse = await neo4j.session(null, cypher.ngp(key, row[key]))
        if (neo4jPropInUse.length !== 0) {
            console.log('IN USE DETECTED')
            const thingResult = Object.assign({}, {
                [thingSerialNumber]: neo4jPropInUse[0].get(`RESULT`).properties[thingSerialNumber],
                key: key
            })
            results = results.concat([thingResult])

        }
    }
}

Answer №1

When an object is declared with const, its contents can still be modified but it cannot be reassigned. If the objective is to have an unmodifiable array after completing a loop, Object.freeze can be used to prevent further modifications to the object (in a shallow manner).

Object.freeze(results);

An attempt to push or pop from the array will now result in an error. It's important to note that this freezing method only applies on the surface level, and changes can still be made to values within objects that are part of the array. Hopefully, this explanation clarifies things.

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

Retrieve a text file using FTP asynchronously and utilizing Promises in Node.js and AWS Lambda

Utilizing a single Node module called basic-ftp, I am tasked with downloading a txt file in AWS Lambda and storing it in the /tmp/ directory within the Lambda function. The goal is to manipulate the txt file and its contents outside of the FTP function. ...

Closing the Bootstrap navbar collapse by clicking anywhere outside of the menu area

Excuse my lack of experience, but I have a question. I am trying to make Bootstrap "navbar-collapse" close when clicking away or on one of the list items. I stumbled upon this code that seems to do the trick. $(document).on('click',function() { ...

Styles in makeStyles use unique css names

Instead of using the const useStyles = makeStyles to style Popover and OtherStyles separately, I want to nest them within Popover, like so: const useStyles = makeStyles({ Popover: { root: { textAlign: "center", ...

Tips for simplifying a JavaScript function

Hello everyone, I just joined StackOverflow and I could really use some assistance with a JavaScript and jQuery issue that I'm facing. Can someone suggest a more efficient way to write the code below?: jQuery(document).ready(function () { $("#ar ...

The Alert Component fails to display when the same Error is triggered for the second time

In the midst of developing a Website using Nuxt.js (Vue.js), I've encountered an issue with my custom Alert Component. I designed a contact form on the site to trigger a specialized notification when users input incorrect data or omit required fields ...

The issue of infinite rendering caused by useState and how to effectively resolve it

I'm facing a strange issue in just a few lines of code, and I can't quite figure out what's happening behind the scenes. Here are the 4 lines causing trouble: function FarmerComponent(props) { let authCtx = useContext(AuthContext) let u ...

The :contains method in jQuery functions smoothly in Firefox, Safari, and Chrome, but unfortunately does not work

My code on JSFiddle is having some compatibility issues with the jQuery :contains selector specifically in Internet Explorer versions 7, 8, and 9. The code works fine in Firefox, Safari, and Chrome. You can find the working code here. I tried making the ...

Ensure to update the canvas prior to the function finishing

Is there a way to update the canvas element while inside a JavaScript function without waiting for the function to return? It can be frustrating when you want to keep the function running but also need to update the canvas element in real time. ...

Watching a service's attribute from within a route in the EmberJS framework

There seems to be a concept that I'm struggling to grasp here. To my understanding, any instance of Ember.object should be able to observe properties on another instance of Ember.object. In my scenario, there is a service, a router, and a component i ...

How can I accurately determine the true dimensions of an image in Angular, including any resizing that may

Here is an image: @ViewChild('image') readonly photo: ElementRef; The HTML code for the image is: <img #photo class="pic" /> How can I find the original size (width, height) as well as the resized dimensions after applying CSS a ...

Button to scroll down

I have successfully implemented a #scrolldownbutton that scrolls to the first component. However, I am now attempting to modify it so that when the button is clicked, the page smoothly scrolls within the viewport and stops at the partially visible componen ...

Modifying button text dynamically during save operation with AngularJS

Is it possible to dynamically change the text on a submit button while data is being saved in a form? Here's an example of the button: <button ng-click="save()">Save data</button> I have updated my save function based on some suggestion ...

Processing made easy with jQuery

In my HTML page, I have multiple rows that represent records from a database. Each row contains input fields and a link at the end. When I click on the link, I need to capture the values of the input fields within the same row. Here is an example of the H ...

What is the best way to change function.bind(this) to an arrow function in a react native application?

I am attempting to convert my function into an arrow function, but I keep encountering an error of undefined when passing props. <TextInput style={styles.input} value={formState.inputValues.title} onChangeText={textCh ...

The sidebar is not correctly displaying at full height

Having trouble getting the sidebar to fit perfectly between the header/nav and footer in full height. <html> <head> <meta charset="utf-8"> </head> <body> <header> <div class="header"> & ...

Having trouble adjusting the color on Material UI select in ReactJS?

Here is the code snippet I am working with: const useStyles = makeStyles({ select: { '&:before': { borderColor: 'white', }, '&:after': { borderColor: 'white&apos ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Inject the code snippet from CodePen into a WordPress webpage

I have a WordPress page where I want to integrate the HTML, CSS and JS code from my Codepen project. The styling appears to be working correctly, but the JavaScript is not functioning as expected. You can view the page here: Could someone assist me in pr ...

Steps to retrieve the latest value of a specific cell within the Material UI Data Grid

After updating the cell within the data grid, I encountered an issue where I could retrieve the ID and field using the prop selectedCellParams, but retrieving the modified value was proving to be challenging. In order to successfully execute the PUT reque ...

Issue with modal dialog not triggering onshow event after postback

In my application, I have a Bootstrap modal dialog that is used to display data when the user clicks on "Edit" in a jQuery data table. The modal contains Cancel and Submit buttons. Everything works correctly when I open the modal, click Cancel, select ano ...