JavaScript's handling of objects and arrays of objects

As I work on developing a web application using AngularJS, my focus is on understanding how references in JavaScript operate. Specifically, I am curious about when changes made to an object impact its references.

For instance, within my application's controller, I handle file uploads and manage file data through a factory.

   $scope.fileArray = [];
    ...
    ...
    uploadFiles(file){
         $scope.fileArray.push(file);
         ..
         ..
         //on success
         file.params = data["parameters"]; //an array of strings about file path and name
         ...
         ...
    }

When I push the file object into the fileArray within the uploadFiles function, any subsequent changes or additions to the file object are reflected in the fileArray.

var fileInfo = {
    infoArray : $scope.fileArray
}

fileFactory.keepFileInfo(fileInfo);

Subsequently, I store this array in the factory. Surprisingly, changes made to `$scope.fileArray` do not get updated in the factory. What could be causing this discrepancy?

EDIT

I stand corrected. Changes to the controller object also influence the factory. To better grasp this concept, I built a basic application demonstrating this flow. It appears that the issue lies elsewhere in my main application.

var testApp = angular.module('testApp', []);

testApp.controller('TestController', function($scope, TestFactory) {
    $scope.fileArray = [];

    var files = [];
    files[0] = {
        parameters : {
            name : 'file1.txt',
            path : "user/files"
        }
    }

    $scope.fileArray.push(files[0]);

    files[1] = {
        parameters : {
            name : 'file2.txt',
            path : "user/files"
        }
    }

    $scope.fileArray.push(files[1]);

    files[2] = {
        parameters : {
            name : 'file3.txt',
            path : "user/files"
        }
    }

    $scope.fileArray.push(files[2]);

    TestFactory.setFileArray($scope.fileArray);

    files[0].parameters["name"] = "changed file name";

    console.log($scope.fileArray); //this will display "changed file name"    
    console.log(TestFactory.getFileArray()); //which will also show "changed file name"
});


testApp.factory('TestFactory', function() {
    var factory = {};

    var fileArray = [];

    factory.setFileArray = function(files) {
        fileArray = files;
    }

    factory.getFileArray = function() {
        return fileArray;
    }

    return factory;
});

Answer №1

Consider this scenario:

var obj1 = {};
var obj2 = {prop: obj1};
console.log(obj1 === obj2.prop);
obj1.subObj = {};
console.log(obj2.prop);

When you assign an object member to another object, they share the same reference. Therefore, modifying one will affect the other. This concept applies to arrays as well:

var obj1 = {};
var arr = [obj1];
console.log(obj1 === arr[0]);
obj1.subObj = {};
console.log(arr[0]);

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

Is it possible to validate input only during insertion in Objectionjs without validation during updates?

const BaseModel = require("./base_model.js"); class CustomerModel extends BaseModel { static get tableName() { return "customers"; } static get jsonSchema() { return { type: "object", required: ['na ...

prevent communication between different domains

Is there a way to prevent other domains from sending POST and GET requests to my domain? I don't trust end users to refrain from doing so, especially considering that the same origin policy can be bypassed. Are there any effective methods for managing ...

Components in Angular 1.x and transitioning between states in ui router version 1

I have 3 main components in my project: App Component Login Component Dashboard Component App Component The app component acts as the root component in the component tree. It contains the basic layout structure such as a header and content wrapper. &l ...

What is the best pattern to utilize for these types of tasks?

I've been struggling a bit with understanding the MVC principle, but I always believed that business logic should be contained within models - please correct me if I'm mistaken. In my current project, I am following the MVC pattern. The rou ...

Checking if a string is present in an array object with Angular.js using a filter function

In my Angular and Firebase app, users can create new discussion topics and vote on existing ones. When a user is logged in, their username is stored in currentUser.username. If they've upvoted a topic, their username will also be added to the array of ...

Is there a way to transform a time string, for instance "8:02 AM", into a sortable field?

I am currently working with a MongoDB database that stores times as strings, and I want to filter queries based on specific time ranges. For instance, the time fields in my database are formatted as "8:02 AM" and "10:20 PM", and I am looking to refine my ...

Import .obj files from user's personal computer using THREE.js

As we all know, HTML5 includes the powerful FileReader API which allows users to load local files based on their selection. However, I am interested in displaying the .obj model that the users have selected. Given that FileReader can only interpret thing ...

Obtain the event object within the Vuex v-model setter method

I am working with a select element that interacts with my Vuex store: <select v-model:value="leadTrackNumber" > <option v-for="(track, index) in tracks ">{{ index }}</option> </select> Here is the corresponding method: leadTra ...

:host ::ng-deep is not properly cascading styles to material checkbox

Struggling with changing the background color of a checkbox in a material multiselect. I've attempted both .mat-pseudo-checkbox-checked { background-color: #a9a9a9 !important; } and :host ::ng-deep .mat-pseudo-checkbox-checked { background-color: ...

Issue arising from the conflict between React script and Jest version 24.7.1

My journey with creating a React app using 'create-react-app' has been smooth so far. I have successfully developed a functional React project. However, the next step of implementing unit testing with jest has hit a roadblock. Upon trying to ins ...

Struggling with a minor glitch in a straightforward coin toss program written in JavaScript

I'm a newcomer to JavaScript programming and I am struggling with understanding how the execution flow is managed. I attempted to integrate an animation from "Animation.css" into a coin toss program, but encountered an issue. When trying to use JavaSc ...

The ui.bootstrap.carousel component seems to be missing from the display

My Carousel is not displaying for some unknown reason. I have customized the implementation based on my project requirements which differ slightly from the standard guidelines. Despite this, it should function correctly as detailed below. By clicking on m ...

Issues with Laravel and AngularJs routing: When a simple route does not trigger the controller

Looking for some assistance with integrating AngularJs into my Laravel application within a blade partial. I have ensured that all necessary files are included, added the ng-app, and verified that there are no JavaScript errors occurring. However, I am enc ...

Set bower to automatically select the precise version instead of a range

When you run a bower install mypackage --save, bower typically uses the tilde range selector (~) prefix to set the latest patch version by default: "angular-ui-grid": "~3.1.0" However, since patch versions can sometimes introduce breaking changes (which ...

Is there a way to give a model of a directive scope a dynamic name while also enabling 2-way binding?

I have a challenge where I need to dynamically pass object values into a directive using ng-repeat. Here's what I've attempted so far: <td ng-repeat="attr in demographicAttrs"> <yes-no name="{{ attr }}-{{ $index }}" model="ambassa ...

Rearrange the order of elements within an array and move elements around within it

I am looking to select an element from an array, relocate it to a different index, and then shift the elements in-between by 1 position. Consider this as drag-and-drop functionality, where if the starting index (from) is less than the destination index ( ...

Using a function with a parameter as an argument in an event handler

Imagine you have the code snippet below: $('#from').focus(listExpand(1)); $('#to').focus(listExpand(3)); I am facing an issue as the code is not behaving as expected. I believe the problem lies in passing a function result instead of ...

Enhancing the aesthetics: Changing placeholder colors easily

::-moz-placeholder { /* Mozilla Firefox */ color: #909; } Is it possible to have unique placeholder colors for various input fields instead of changing the color of all placeholders at once? ...

What is preventing my form from submitting on its own?

Is there something wrong with submit()? It doesn't seem to be working for me. <html> <head> <title>This is the title</title> <script type = "text/javascript"> function onLoad() { document.get ...

My goal is to implement a confirmation modal prior to any route changes within Next.js framework

Below is the code block that I have: const onRouteChangeStart = React.useCallback(() => { if (formState.isDirty) { if (window.confirm('Confirmation message')) { return true; } NProgress.done(); throw "A ...