Without utilizing any specific reference to an object in a programming language that is commonly

Here is the situation:

req.session.user = doc[0];
req.session.user.password = null;

This results in doc[0].password = null!

How can I avoid this from happening?

Edit: Assuming that

doc[0] = { name: 'sangram', e-mail: 'abc.in', password : 'pwd' }

Answer №1

To achieve this, you can replicate all properties of an object:

req.session.user = {};
for (var key in user) {
  if (key !== 'password') req.session.user[key] = user[key];
}

If the user object is a mongoose document, it's recommended to first convert it to a plain object:

req.session.user = {};
var json = user.toObject();
for (var key in json) {
  if (key !== 'password') req.session.user[key] = json[key];
}

Alternatively, using a helpful library like underscore or lodash can simplify the process:

req.session.user = _.omit(user.toObject(), 'password');

Answer №2

To handle basic scenarios involving simple objects, a compact helper function was created:

function CloneObject(obj) {
    var duplicate = {};
    for (var prop in obj)
        duplicate[prop] = obj[prop];
    return duplicate;
}

Here's how you can use it in your specific situation:

req.session.user = CloneObject(doc[0]);
req.session.user.password = null; //does not impact the password in doc[0]

Check out the live test case here. (using a sample object)

Answer №4

It is not possible to prevent this scenario. The user attribute is already set to the object doc[0]. Subsequently, when you modify the .password attribute of this newly assigned object, it will affect the original object as well. To segregate the password, you must assign a different object to doc[0].

req.session.user = {};
req.session.user.doc = doc[0];
req.session.user.password = null;

Below is a function for duplicating/extending an object:

var duplicate = function() {   
    var process = function(target, source) {   
        for (var property in source) {
            if (Object.prototype.hasOwnProperty.call(source, property)) {
                target[property] = source[property];
            }
        }
        return target;
    };
    var output = arguments[0];
    for(var j=1; j<arguments.length; j++) {
        output = process(output, arguments[j]);
    }
    return output;
};

An example of how to utilize the function:

var initial = { value: "hello" };
var copied = duplicate({}, initial, { newAttribute: "example"});

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

jQuery animation that smoothly fades out from the left and fades in from the right

This survey is designed to assist individuals in determining where they should go with a specific type of ticket. Currently, everything is functioning smoothly, but I would like to add a sleek animation to each ul transition. Whenever a button is clicked ...

Retrieving exclusive npm packages from an npmjs user

I am currently facing a challenge with transferring all of our npm modules from npmjs.com to a new location. The issue is that our modules are saved under a private npm user account, making it difficult for me to programmatically access and consume all the ...

Is there a way to remove a function from a constructor in JavaScript?

Is it possible to remove a function from a constructor? If the constructor for a Person object contains a function named greet, how would one go about eliminating this function? function Person(name) { this.name = name; ...

The result returned by Array.isArray is false

As someone diving into the world of javascript and currently unpacking destructuring, I stumbled upon a puzzling snippet that sparked a question in my mind. After some editing, my code was identified as an array by the console, which left me scratching my ...

Encountering varying outcomes in Internet Explorer and Chrome when converting a UTC date and time to a local date and time by utilizing the getTime

My current approach involves converting UTC date time (received from the server in the format 2017-01-25T23:08:08.453) to local date time on the browser using JavaScript. I do this without asking the user for their timezone details, and assuming that the s ...

There was a unique key error in the "products" collection of the database. The index "product_id_1" had a duplicate key with a value of

Seeking assistance urgently! I've been facing a blockage for the past two days in retrieving all my products. An error involving duplicate keys is hindering the GET action. Despite attempting various methods such as remove({}), deleteMany({}), or comb ...

Building a custom HTML and JavaScript player to showcase multiple videos on a webpage

UPDATE: The solution has been discovered, shared, and marked as the top answer below. In the process of creating my portfolio website using HTML, CSS, and JS, I encountered a challenge regarding the addition of multiple videos on various pages. While fol ...

Leverage an array to streamline the filtering process in Prisma with Next

If I have an array of unique names, how can I update the elements of those names using Prisma in Next.js? For example: const arr=['Joe', 'Mark']; const update=await prisma.user.updateMany({ where: { name: //What should be us ...

Transform an Array by replacing a specific value or creating a new one

Dealing with two arrays, both potentially of large lengths: The goal is to update the status in Array 1 with the corresponding status from Array 2. Here's a sample output: [{ value: 123, status: 'demo', type: '...' }, {value: 233 ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

Unable to get knockout sorting to function properly

I have been working on organizing my grid and here is the code that I have so far: ko.moveInGrid = { // Creating a view model class for grid population viewModel : function(config) { this.data = config.data; this.currentPageIndex = ...

How can I apply styling to Angular 2 component selector tags?

As I explore various Angular 2 frameworks, particularly Angular Material 2 and Ionic 2, I've noticed a difference in their component stylings. Some components have CSS directly applied to the tags, while others use classes for styling. For instance, w ...

Ensure that both Vue methods are executed synchronously

I am working with two Vue methods: (1) this.retrieveSavedSearches() (2) this.updateDefaultSelectOption() Is there a way to ensure that method (2) only executes after method(1) has completed its execution? ...

React Router: Navigating to a Route Becomes Problematic with useNavigate Hook

I am currently developing a React application that utilizes React Router for navigation purposes. One specific component named ShowNotes is causing some issues with the implementation of a "Delete" button, which is intended to redirect to the "/DeleteNotes ...

Heroku asset precompilation just got easier!

Most online resources focus on Rails for asset building during slug compilation. I'm curious if there are methods to achieve the same in other languages such as Node.js or PHP? ...

Adjust the height of a DIV element using Jquery Resizable to a minimum height of 1px, smaller than its default value

Having an issue with the Jquery UI Resizable functionality. I've implemented Jquery resizable to adjust a div's width and height dynamically. It's been working well, but I'm encountering a problem when attempting to decrease the height ...

Safari experiencing CORS violation while Chrome is unaffected

I'm encountering an issue with my React web app that communicates with an Express web server. While everything functions correctly in Chrome, I'm facing an error when accessing the app in Safari: XMLHttpRequest cannot load https://subdomain.exam ...

Having trouble with jQuery's getJSON function throwing an error?

I have been working on a project where I am using the getJSON function to fetch JSON data from an API that I am developing. However, I am facing an issue where the getJSON function always triggers the error handler. Below is the JavaScript code I am using: ...

CSV data extraction in Node.js is malfunctioning

I am currently utilizing nodejs v0.10.26 and expressjs. I have a requirement to include data export functionality in CSV format within my application, and for this purpose, I am utilizing node-csv version 0.3.7. JS var csv = requ ...

Having difficulty passing an array using AJAX

One of my current projects involves using a JavaScript function to send an array via AJAX to a PHP script on the server side. Below, I am including relevant excerpts of the code from my JavaScript AJAX function: $.ajax({ url: "bar2.php", type: ...