How to assign a locally created array in a function to a globally defined array in JavaScript

Whenever I try to assign arrays, a problem arises:

    var arr = [ {'id': 1, 'size': 'large' }, {'id':4, 'size': 'small'} ];
    function adjust(a){
      var result=[{'id': 1, 'size': 'large'}];
      a=result.slice();
    }
    adjust(arr);
    document.write("result:" + JSON.stringify(arr)); //arr contains both 'large and small'

I wish to populate 'arr' with the data from the 'result' array, but this method doesn't seem to work. However, it is possible to clear the array and update its content in this manner:

    a.length=0;//arr is now empty outside of the function
    a[1].id = 100;//changing id value outside of the function

I am aware that I could achieve this by returning the 'result' array and assigning it externally to 'arr', but there will be many such connections within the function. Any guidance on resolving this issue would be highly appreciated. Thank you

Answer №1

If you're looking to incorporate the assignment within a function, there are two approaches you can take. One method involves changing the content of obj and passing it as a parameter:

var obj = [ {'id': 1, 'size': 'king' }, {'id':4, 'size': 'queen'} ];
function update(o){
  var result=[{'id': 1, 'size': 'king'}];
  o.length = 0;
  o.push.apply(o,result); // adding each element from result
}
update(obj);
console.log(obj);

Alternatively, you can modify the reference to another value. In this scenario, you must manipulate the actual variable rather than a function parameter:

var obj = [ {'id': 1, 'size': 'king' }, {'id':4, 'size': 'queen'} ];
function updateObj(){
  var result=[{'id': 1, 'size': 'king'}];
  obj = result.slice();
}
updateObj();
console.log(obj);

An enhanced version of the second approach is to store your array within an object, but this adjustment will impact how you access it in your code:

var container = { 
  obj : [ {'id': 1, 'size': 'king' }, {'id':4, 'size': 'queen'} ] 
};
function update(container, key){
  var result=[{'id': 1, 'size': 'king'}];
  container[key] = result.slice();
}
update(container, 'obj');
console.log(container.obj);

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

Count of jSon objects

After receiving a string st from a web service, I convert it into an object. How can I determine the number of arrays inside this object? In this particular case, there are 2 arrays. var st = "{[{"Name": "fake", "Address": "add"]},[{"Name": "fake", "Addre ...

Struggling to integrate Ajax with Angular framework

Looking to learn Angular. Attempting to integrate Angular with AJAX calls. Whenever I try to access http://localhost:9091/jerseyservlet/jerseyrest/org/orgId/DEY using a browser or any REST client, the following response is displayed: <users> & ...

Struggling to make PayPal Cordova Plugin function properly in both production and sandbox modes

While using the cordova paypal plugin and switching to sandbox mode, I encountered an error. The plugin can be found at https://github.com/paypal/PayPal-Cordova-Plugin https://i.stack.imgur.com/lD2EH.png Running the plugin in PayPalEnvironmentNoNetwork m ...

When using the `style` prop, it is important to provide a mapping of style properties to their corresponding values, rather

import React, { Component } from 'react'; class App extends Component { render() { const title = 'Bold Text'; const boldStyle = {fontWeight: 'bold'}; return ( <div style="{boldStyle}"> {title} < ...

Adjust the location.hash and then navigate using the Back button - Internet Explorer displays unique behavior compared to other web browsers

When updating `location.hash`, all browsers behave correctly by only changing the URL without refreshing the page. However, pressing the Back button in Internet Explorer and other browsers results in different behaviors. IE fails to update the history wit ...

Searching in MongoDB using regular expressions, starting with the JavaScript driver in a Node.js environment

Currently, I am utilizing the JavaScript MongoDB driver from Node.js. My objective is to execute this query within my JavaScript function: db.mycollection.find({Zip:/^94404/}); Upon running the above query, the mongo client successfully retrieves 8 docum ...

Unexpected behavior encountered with Angular module dependency injection

Having some difficulty managing dependencies for my node app. Here's the current structure: app.js var app = angular.module('myApp', ['myController', 'myFactory', 'rzModule', 'chart.js', 'myServ ...

Troubleshooting Ajax contact form's failure to refresh (PHP and Bootstrap 4)

I have successfully implemented this code on one website, but it is not working as expected on another website. It sends the email but refreshes the page and redirects to a contact.php page with a message. Despite double-checking everything, including cha ...

Transferring information from a component to a service file in Angular 2

I am currently working on implementing a search functionality in my Angular app. In my app.component.html, I have the following code snippet: <input type="text" [(ngModel)]="keystroke"> {{keystroke}} <!-- prints out each keystroke --> In addi ...

Prevent clicks from passing through the transparent header-div onto bootstrap buttons

I have a webpage built with AngularJS and Bootstrap. It's currently in beta and available online in (German and): teacher.scool.cool simply click on "test anmelden" navigate to the next page using the menu This webpage features a fixed transparent ...

The system encountered an error while trying to access the property 'enabled' of an undefined object

When working on a reactive form in my code, I need to ensure the values are properly set for the controls. ngDoCheck() { setControlValues(); } ngChanges(changes: SimpleChanges): void { setControlValues(); } private setControlValues() { try { ...

The export "hasInjectionContext" is not provided by the source file "node_modules/vue-demi/lib/index.mjs", but it is being requested in the file "node_modules/pinia/dist/pinia.mjs"

Every time I launch my program, the console displays an error message stating that "hasInjectionContext" is not exported by "node_modules/vue-demi/lib/index.mjs", imported by "node_modules/pinia/dist/pinia.mjs" at line 6:9. I ...

utilizing ajax to submit data with checkbox option

<html> <body> <input type="checkbox" checked="checked"> </body> </html> I am looking for a solution to pass the value of a checkbox as either 1 or 0 depending on its selection status. When the checkbox is checked, I want to s ...

Issue with ng-model causing incorrect variable binding

My issue lies with a variable that I have connected to a select input through the use of ng-model. Strangely, the variable seems to not update with the correct data and retains the value assigned to it during initialization. I have a similar setup elsewhe ...

What is causing the object, which is clearly defined (as shown in the callback to JSONLoader), to be interpreted as undefined

Why is the THREE.Mesh() object showing as undefined even though it was defined in a THREE.JSONLoader()? Here is the code snippet... 1: var player; 2: var playerCallback = function(geo, mats){ 3: player = new THREE.Mesh(geo, new THREE.MeshFaceMaterial( ...

Issue encountered while attempting to load a JSON file into an ExtJS JSONPStore due to a

After validating a json file with json.bloople.net, the file begins as follows: { "sepString": "--", When attempting to load this json file into an ExtJS JsonPStore, Chrome displays the error: Uncaught SyntaxError: Unexpected token : in line 2 What ...

The cookie appears in the callback URL, but does not get stored in the browser's cookie storage

I'm attempting to store the facebookPicUrl image in a cookie. Even though I can see it in the callback request, it's not showing up in the browser's cookie storage. Just to clarify, the session cookie is working fine. auth.route('/auth ...

Is there a convenient method to combine arrays of objects in JavaScript using ellipses or an equivalent approach?

let array = [ {id: 1, data: {foo: "bar 1"}}, {id: 2, data: {foo: "bar 2"}} ]; //If ID doesn't exist, add new element to the array array = [...array, {id: 3, data: {foo: "bar 3"}}] console.log(array); //If ID exists, replace data object with new ...

Unlock the Power of Rendering MUI Components in ReactJS Using a For Loop

Hey there! Hope everything is going well. I've been working on a fun project creating an Advent/Chocolate Box Calendar using ReactJS. One challenge I'm facing is figuring out how to iterate over a for loop for each day in December and render it ...

Ensure the vertical dimension of the webpage is properly maintained

I am currently working with a client who has requested a website design with a specific height for the content section. The Inquiry: Is it possible to automatically create a new page for text that exceeds the maximum height of the content section on the ...