Manipulating an element in the JSON data is causing alterations to the preceding elements

I am facing a challenge with two JSON arrays.

 $scope.arr1 = [
            { "id": 1, "first_name": "Philip", "last_name": "Kim", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6e7577732e5e737b7a777f78776c7b307d7173">[email protected]</a>", "country": "Indonesia", "ip_address": "29.107.35.8" },
            { "id": 2, "first_name": "Judith", "last_name": "Austin", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="543e352127203d3a651439352425213127207a373b39">[email protected]</a>", "country": "China", "ip_address": "173.65.94.30" },
            { "id": 3, "first_name": "Julie", "last_name": "Wells", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117b66747d7d622351787d7d787f7e78623f747564">[email protected]</a>", "country": "Finland", "ip_address": "9.100.80.145" },
            { "id": 4, "first_name": "Gloria", "last_name": "Greene", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99fefeebfcfcf7fcaad9fbf5f6feeab7faf6f4">[email protected]</a>", "country": "Indonesia", "ip_address": "69.115.85.157" },
            { "id": 5, "first_name": "Andrea", "last_name": "Greene", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6a7a1b4a3a3a8a3f286a0a2a7e8a1a9b0">[email protected]</a>", "country": "Russia", "ip_address": "128.72.13.52" }]

$scope.arr2=[];

I aim to transfer elements from arr1 to arr2 one by one based on specific conditions.

var object;
var temp = {};

  for (var i in $scope.arr1) {
    object = $scope.arr1[i];
       for (var property in object) {

            temp2 = object.id + '_' + property;
            if ($scope.someOtherData.indexOf("unhighlighted") != -1) {
               temp[property] = "";

              }
             else {

               temp[property] = object[property];

             }
          }
        $scope.arr2.push(temp);
      }

My primary inquiry is regarding the issue I encounter when pushing values from temp to arr2. Subsequent pushes result in all elements in arr2 taking the last temp value. How can this be resolved?

Secondly, I have noticed the spontaneous occurrence of adding $$hashKey attribute to arr1. Is there a way to prevent this from happening?

Answer №1

One of the issues arises from how JavaScript handles objects, as they are passed by reference. To explain, in your code, variable temp is declared globally within the loops. This means that when you update the values of temp in the second loop, you are actually updating the same object that was pushed into the array. Essentially, you are pushing the same object multiple times into the array, and any changes made to one will affect all instances since they all point to the same object.

To address this issue, here are two fixes:

1) As others have suggested, create a new object in each iteration of the loop so that there are no reference issues. The updated code would look like this:

   for (var i in $scope.arr1) {
    object = $scope.arr1[i];
    var temp = {};  // creating new object in every loop
    for (var property in object) {
      //your stuff

2) Prior to pushing the object into the array, make a clone of it to ensure that new objects are added each time. The revised code would be as follows:

 var newObject = Object.clone(temp); // create a new object by cloning
   $scope.arr2.push(newObject );

Answer №2

Ensure to initialize the variable temp before entering the for loop:

for (var i in $scope.arr1) {
   object = $scope.arr1[i];
   var temp = {};  //<--------make sure to declare it here
   for (var property in object) {

Answer №3

To avoid updating the same object by reference, it's important to create a new object for each iteration.

Currently, you are repeatedly adding the same object to array2 which results in having multiple copies of the same object in array 2.

// Use this method to prevent using the same object
var temp = {};
for (var property in object) {
     // Add code here to avoid copying unnecessary properties
     if(object.hasOwnProperty(property))
     {         
        ... 
     }   

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

Retrieving the selected value from a Bootstrap dropdown using JavaScript when there are multiple dropdowns present

I have created multiple rows in javascript that are being rendered to the DOM from a Firestore collection. Each row contains a Bootstrap dropdown with the same select options (".a" elements). The id attribute of each row div is dynamically set based on the ...

What is the best way to upgrade Angular from version 10 to 12?

Currently tackling an Angular project migration from version 10 to version 12. Unfortunately, the project seems to be encountering issues post-migration and is not running as expected. ...

Integrate the perfect-scrollbar jQuery plugin into RequireJS

Recently, I decided to explore RequireJS for my projects but I am still trying to understand its functionalities. I'm currently attempting to incorporate perfect-scrollbar, specifically the jQuery version, into my work. Here's a snippet from my ...

Discovering the Power of IONIC with JSON Data Suggestions

Which method is more effective for handling JSON data, especially when working with IONIC? var quizs = [ {id: 1, question: '1.jpg', desc: 'What color is displayed here', answer: 'blue, green, ...

Exploring the interaction of karma, jasmine, Angular, and UI router through testing the resolve function when using state.go with parameters

In my Angular module "moduleB", I have the state defined as shown below: $stateProvider .state('stateB', { parent: 'stateA', abstract: true, templateUrl : base ...

The JSON parser has exceeded the permitted memory allocation of 134217728 bytes and cannot allocate additional 72 bytes, resulting in an error on line 14 of the /home/migrande/public_html/sample.php

Could someone lend a hand with this code? I'm trying to retrieve all the data from the database using PHP JSON... but how can I make it work? <?php require_once 'include/db_functions.php'; $db = new DB_Functions(); $user = $ ...

Utilize associative arrays to efficiently filter ng-repeat

Having an associative array (or object to be more precise) $scope.items = { 'x': {...}, 'y': {...} }; Wanting to use ng-repeat which is functioning properly <div ng-repeat="(id, data) in items | filter: customFunction" > But t ...

Is there a way to determine the quantity of items within a sortable div?

In my HTML document, there are multiple divs containing smaller divs that can be rearranged within each other. Upon loading the document, a random assortment of these smaller divs are added to #boxtop. Below is a snippet of my HTML code: <html> &l ...

Issue with AngularJS factory $http.get request receiving HTML files as response

Could someone please explain why I keep receiving an HTML file as a return from my Angular factory? This is the route on my backend: function ensureAuthenticated(req, res, next) { if (!req.headers.authorization) { return res.status(401).send({ mess ...

"What is the best way to eliminate duplicate data from an ng-repeat loop in AngularJS

I have a query regarding appending data from the second table into $scope.notiData in AngularJS. Additionally, I need to figure out how to remove ng-repeat data when the user clicks on the remove symbol X. I have attempted some code but it is not functioni ...

I encountered an issue while attempting to fetch table data, receiving the following error message: "Uncaught TypeError: result.rows.product is not a function at products.html:134."

https://i.sstatic.net/WZ5CC.pngHere is the HTML I have written <form> <br/> <label for="products1">Product Name:</label> <input type="text" name="pdt" id="pr ...

Sharing CSS styles among multiple single-page applications (SPAs) developed using the React

I am currently working on multiple micro SPAs that exist independently within an Express environment. I am facing a challenge with importing a global CSS file that is located outside of the apps, as it is not being recognized. The use of @import url(asset ...

Change occurring within a cell of a table that has a width of 1 pixel

In the code snippet below, there is a transition inside a table cell with a width of 1px to allow it to wrap its content. However, the table layout changes only at the end or beginning of the transition: var animator = document.getElementById("animator" ...

The execution of Node.js on data is triggered only after the content has been successfully written

Hello, I am attempting to establish a connection to a telnet server using Node's net library. const net = require('net'); const con = new net.Socket(); con.connect(23,'10.0.0.120', () => { console.log('Telnet connected ...

Exploring the varying treatment of the noscript tag across different web browsers

I've been searching everywhere, but I can't find any information on this topic. What I really want to understand is what browsers do with the content inside a noscript tag when JavaScript is enabled. Let's consider an example: According t ...

Exploring the power of AutoIt in iterating through a JSON array

I'm in need of assistance with automating a script to loop through an array and return a specific value from each object. [{"var1":"test1","var2":"test1"},{"var1":"test2","var2":"test2"},{"var1":"test3","var2":"test3"}] My goal is to extract the var ...

JSON encountered a surprise token ? at the beginning position, leading to an error

I am currently facing an issue with a get request in node.js to a specific URL that returns an object I need to parse. Despite my efforts, I keep encountering the unexpected token error. I have tried experimenting with different encodings and even converti ...

Create a list with interconnected input fields for duplication

I'm new to javascript and I have a question. I'm working on duplicating a list that has input fields for each option. The duplication is working fine, but the associated input fields are not showing up in the duplicated list. Additionally, I woul ...

Element mysteriously concealed in certain Safari cases, consistently visible in Firefox and Chrome

A new angular application has been developed as a "bounce" page for an upcoming social iOS app currently in public beta. Users have the ability to share their profiles by simply providing a link to the site. If the page is accessed via an iOS device w ...

Update your mappings for the city of Istanbul when utilizing both TypeScript and Babel

Currently, I am facing the challenge of generating code coverage for my TypeScript project using remap Istanbul. The issue arises due to the usage of async/await in my code, which TypeScript cannot transpile into ES5 directly. To circumvent this limitation ...