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

reveal.js: Upon a fresh installation, an error has been encountered: ReferenceError - 'navigator'

Currently, I am attempting to integrate reveal.js into my React.js/Next.js website using the instructions provided at However, upon implementation, I encountered the following error: Server Error ReferenceError: navigator is not defined This error occurr ...

Using setTimeout with drag and drop functionality in HTML

I need a setTimeout function to be triggered only after dragging and dropping an image into a division, not before the drop occurs. ...

Utilizing JavaScript to call functions from an ASP.NET code file

I am in need of assistance with integrating a JavaScript-based timeline that requires data from an SQL server. I have already developed the queries and JSON conversions using C#.NET functions within a code file associated with an .aspx page. As a newcomer ...

Tips for displaying the overlay in a jQuery UI modal dialog

The demonstration shows that the overlay is displayed correctly and all elements below it are disabled: <div class="ui-widget-overlay" style="width: 1920px; height: 650px; z-index: 1001;"></div> However, on my webpage, I am still able to inte ...

Using a split string to destructure an array with a mix of let and const variables

There is a problem with TS: An error occurs stating that 'parsedHours' and 'parsedMinutes' should be declared as constants by using 'const' instead of 'prefer-const'. This issue arises when attempting to destructure ...

Having difficulty with Axios due to the URL containing a potent # symbol

When I pass a URL in axios, such as: https://jsonplaceholder.typicode.com/todos/#abc?pt=1 I only seem to receive the base URL in my network requests: https://jsonplaceholder.typicode.com/todos/ If anyone has insight on correctly passing URLs with #, yo ...

Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below: <div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id"> & ...

Alter the value of a key within a JSON object at a specific nested level using Node.js or JavaScript

I am attempting to swap out a specific value in the JSON file. Let's say the JSON data provided below: sample.json let sample={ "yuiwedw":{ "id":"yuiwedw", "loc": "ar", "body":{ "data":"we got this", "loc":"ar", "system":{ ...

Error alert: The system could not locate Google when trying to drop pins

Every time I attempt to place pins on the map, I encounter the "google is not defined" error. The map itself displays without any issues until I add the lines following the initMap() function. I have come across similar posts but none of the suggested so ...

Retrieving information within a Vue component

I am struggling to access some data I have bound to a component without success. How can I achieve this? Below is my component: export default { name: 'component-vallingby', data() { return { } }, created() {}, methods: {} } And h ...

The icons from FontAwesome in Vue do not update when computed

I am seeking a way to dynamically change the header icon based on a conversation property. <a class="navbar-item" :title="$t('header.lock')" @click="makePrivate"> <i class="fas" :class="getLockClass"></i> </a> These ...

Click-triggered CSS animations

Trying to achieve an effect with regular JS (not jQuery) by making images shake after they are clicked, but running into issues. HTML: <img id='s1_imgB' class="fragment"... onClick="wrongAnswer()"... JS: function wrongAnswer(){ docume ...

Adding an array to JSON using PHP

I have extracted a group of IP addresses from a database and I need to embed them into a JSON object as an array. Below is the JSON structure: $jsonString="{ \"id\": 1, \"type\": \"service\", \"n ...

Struggling to retrieve the value in Node.js

Currently, I am in the process of developing a Node.js script to perform the following tasks: Read a file line by line Identify a regex match and store it in a variable Utilize this value in subsequent operations Below is the code snippet that I have im ...

Using an element with the href property in conjunction with react-router: a comprehensive guide

My goal is to implement the navigation.push(url) functionality upon clicking an anchor tag element in order to prevent the app from refreshing when navigating to a new page, thus allowing me to maintain the application state. The decision to use this on a ...

Determine the value above a certain price point by utilizing JSON operators

Json: "availability": [ { "qty": 25, "price": 3599, "is_available": true }, { "qty": 72, "price": 3599, }, "is_avai ...

Error in Protractor HTML screenshot reporter displaying message as 'undefined'

I am seeing 'undefined' displayed in the message section of the html report generated by the Protractor-Html-Screenshot reporter. I am utilizing chai.assert in my tests, so it should display 'Passed' for scripts that have passed success ...

What could be the reason for the unexpected outcome when checking if display is equal to "none"?

I have a JavaScript function called "display()". I want to hide my navigation menu on click, but it is not working properly - it just blinks. I am looking for a solution that uses only JavaScript and does not involve querySelector. function display() { ...

Utilizing Chart.js for generating a sleek and informative line graph

After executing a MySQL query, I obtained two tables named table1 (pl_pl) and table2 (act_act) with the following data: table1: label act_hrs Jan-19 7 Feb-20 8 Mar-20 9 table2: label pl_hrs Mar-20 45 Apr-20 53 I am looking to create a line cha ...

Experiment with the Users.Get function available in vk-io

I am having an issue with a create command: Ban [@durov] and I encountered an error. Here is how I attempted to solve the problem: let uid = `${message.$match[1]}` let rrr = uid.includes('@') if(rrr == true){ let realid = uid.replace(/[@]/g, &ap ...