Updating the value of an element in a JavaScript array

Having the JSON Array provided below, my current challenge is in adding a new object to one of the array elements. The issue arises when attempting to push a new object into the array array1 at index 0 of arrayHolder, as it leads to all existing array1 elements being updated with the new object.

{
  "arrayHolder": [
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}

The code snippet below demonstrates how I am currently pushing to array1:

var jsonStr = "{\"arrayHolder\":[{\"array1\": [],\"....."; // Represents the Json String
var jsonObj = JSON.parse(jsonStr); // Convert string to an object 

var newObj = {"value": 1}; // New object meant to be pushed 
jsonObj.arrayHolder[0].array1.push(newObj);

// A similar approach yields similar results
jsonObj.arrayHolder[0]["array1"][0] = newObj;

The resulting output shows:

{
  "arrayHolder": [
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}

The desired outcome is to update the value of array1 solely for the element at index 0 within the arrayHolder array, while leaving the other array1 elements untouched in the main array.

Answer №1

There seems to be a problem with the array holder as it is referencing the same object, resulting in changes made in one place being reflected everywhere.

Answer №2

If you're experiencing issues with your current solution, @ehab has provided an explanation as to why it's not working. The problem lies in using the same object to complete object x, since objects and arrays are Reference types in Javascript.

var x={
  "arrayHolder": [
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}
 var jsonStr =JSON.stringify(x)// Json String
var jsonObj = JSON.parse(jsonStr); // String To object 
debugger
var newObj = {"value": 1}; // New object that I want to push 
jsonObj.arrayHolder[0].array1.push(newObj);

result=JSON.stringify(jsonObj)
console.log("result:"+result)

result:{"arrayHolder":[{"array1":[{"value":1}],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]}]}

Answer №3

Experiment with:

jsonObj.['arrayHolder'][0]['array1'].push(newObj);

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

Convert the easeInExpo function from jQuery easing to vanilla JavaScript and CSS

Currently, I am in the process of converting a piece of code from jQuery to plain JavaScript and CSS. The specific code snippet I am focusing on involves creating easing functions without relying on jQuery. const customEasing = { easeInExpo: function ( ...

Having trouble with $.ajax? I can't seem to get it to hit my controller action. Can anyone provide

Seeking assistance. I need help with the following code snippet: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <script type="text/javascript> function GOTO() { var datastring = "id=2"; $. ...

Exploring the options available for setting types in Angular-formly

While using setType to create a new type in angular-formly, how can I show the options in the template? I am trying to create a type called "category" that will display the label on the webpage. How can I retrieve the label name? This is what my code loo ...

AngularJS continues to display an "Invalid Request" message whenever the requested resource is unavailable

When I try to fetch a group of images through AJAX and exhibit them on the page using ng-repeat, an issue arises with the image source tags. These tags send incorrect requests to the server before the collection is retrieved, leading to error messages in t ...

Trouble receiving a reply from the Angular controller

I'm a newcomer to AngularJS and I'm currently working on integrating AngularJS into one of my existing applications. Below is the provided HTML and JavaScript code: <!doctype html> <html ng-app="ldlApp"> <head> <script src= ...

Using PHP to send a JSON request via cURL

I am attempting to make a cURL request in PHP. The request I am trying to send is as follows: $ curl -H 'Content-Type: application/json' -d '{"username":"a", "password":"b","msisdn":"447000000001","webhook":"http://example.com/"}' http ...

Issue encountered while attempting to set up react-native project

Whenever I attempt to create a new react-native project using the command: npx react-native init myproject I encounter the following errors: ERESOLVE is overriding peer dependency npm gives me a warning while trying to resolve: [email protected] ...

What is the best way to interpret JSON data in Swift?

I am working with an API JSON response that looks like this. My goal is to decode the JSON in order to obtain an array of dictionaries [String:Double], similar to [{"2020-01-01" : 0.891186}, {"2020-01-02" : 0.891186}]. { "rates": { "2020-01-01" ...

Creating a dynamic directive in AngularJS: Learn how to add or remove it from the DOM based on specific conditions

Suppose I have a customized modal directive that looks like this: return { restrict: 'E', templateUrl: 'modal.html', scope: { modalContent: "&", modalOpen: "&" } } And in the HTML: <ng-modal modal-content="co ...

The smooth scrolling feature of jQuery does not function properly when combined with the Bootstrap 4 Navbar

Here is the code I have for the navigation bar on a website I am currently working on: <body data-spy="scroll" data-target="#navbar" data-offset="20"> <!-- navbar --> <div id="home"> <div id="navbar"> <nav class="n ...

Guide on redirecting the user to the "notFound" page within the getServerSideProps function in Next.JS whenever an incorrect params.id is provided

export const getServerSideProps = async ({ params }) => { const res = await fetch( `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${params.id}` ); const { hits } = await res.json(); if (!hits) { return { notFound: tr ...

Using JQuery validate to extract the interest rate from a regular expression

I am looking for a regular expression that can extract the interest rate. I need it to accept values such as: Examples: 0 0.4 0.44 4 44 4.00 44.00 4.2 4.22 44.22 Minimum value allowed is 0 and maximum is 99.99 The regular expression should be ab ...

Using Javascript in React Native to filter an object within an array

Struggling with a seemingly trivial issue here. Despite numerous attempts, I can't seem to find a solution. Any suggestions? I currently have an array populated with objects structured like this: [ Object { "name": "name", "descrip ...

Posting several pictures with Protractor

In my test suite, I have a specific scenario that requires the following steps: Click on a button. Upload an image from a specified directory. Wait for 15 seconds Repeat Steps 1-3 for all images in the specified directory. I need to figure out how to up ...

When should you utilize the Safe Navigation Operator (?.) and when is it best to use the Logical AND (&&) operator in order to prevent null/undefined references?

Imagine having an object property (let's call it arrThatCouldBeNullOrUndefined: SomeObjType) in your Angular component. You aim to perform an array operation (let's say filter() operation) on its data: DataType[] object and save the result in an ...

Harnessing the Power of JSON Data Extraction with JavaScript

I stored the data in JSON format using the setItem method: localStorage.setItem('orderproduct', JSON.stringify([{imageSource: productImg, productTitle: title, productQuantity: qty, productPrice: finalprice}])); When I inspect it, this is how it ...

Handling Asynchronous API Requests with AngularJS

I am facing an issue with displaying data from API in my files foo.js and foo.html. While fetching information asynchronously in foo.js, I store it in an object that should be accessible in foo.html. However, despite receiving the data correctly, I am una ...

Learn how to extract substrings from a variable within an API using Vue.js

Exploring VueJs for the first time and looking to split a string by comma (,) retrieved from an API into separate variables. The data is coming from a JSON server. "featured-property": [ { "id": "1", " ...

Differences between JavaScript array manipulation using the split(" ") method and the spread operator

I'm currently attempting to determine if a given sentence is a palindrome, disregarding word breaks and punctuation. The code snippet that utilizes cStr.split(" ") DOES NOT achieve the desired outcome. Although it splits on whitespaces (&qu ...

Is there a way to incorporate both max-width and min-width in a matchMedia query effectively?

I'm currently utilizing the matchMedia API in my JavaScript code to identify viewports, with the goal of reducing DOM manipulations. Instead of using display: none extensively, I am opting for a v-if directive from Vue to determine when elements are ...