Looking for assistance with a JavaScript code snippet

I have encountered an issue while iterating through receipts in the given code snippet. The objective is to fetch the receipt number for each receipt and add it to a JSON object. However, I am facing a problem where the same receipt is appearing in two separate JSON objects. Can anyone provide assistance with this matter? Thank you in advance.

const shopList = [];
const shop = {
"shopNumber": "2242461",
"shopDate": "2020-06-13T00:00:00.000-05:00",
"shopAmount": "100",
"shopBank": "HDFC",
"shopDetails": {
    "shopNumber": "1242461",
    "shopDate": "2020-06-13T00:00:00.000-05:00",
    "shopBank": "HDFC",
    "shopAmount": "100"
},
"receiptDetails": [{
        "userNumber": "115729",
        "receiptNumber": "temp1"
    },
    {
        "userNumber": "115726",
        "receiptNumber": "temp2"
    }
]

};
 shop.receiptDetails.forEach((receipt) => {
var temp = shop.shopDetails;
temp.receiptNumber = receipt.receiptNumber;
shopList.push({
    shopNumber: shop.shopNumber,
    userNumber: Number(receipt.userNumber),
    receiptNumber: receipt.receiptNumber,
    shopDetails: temp,
    isSync: 0
});
});
shopList.forEach((receipt) => {
console.log(receipt);
});

The current output shows:

{
shopNumber: '2242461',
userNumber: 115729,
receiptNumber: 'temp1',
shopDetails: {
    shopNumber: '1242461',
    shopDate: '2020-06-13T00:00:00.000-05:00',
    shopBank: 'HDFC',
    shopAmount: '100',
    receiptNumber: 'temp2' ----**this should be temp1**
},
isSync: 0
} {
shopNumber: '2242461',
userNumber: 115726,
receiptNumber: 'temp2',
shopDetails: {
    shopNumber: '1242461',
    shopDate: '2020-06-13T00:00:00.000-05:00',
    shopBank: 'HDFC',
    shopAmount: '100',
    receiptNumber: 'temp2'    
},
isSync: 0
}

Answer №1

The reason for this behavior is due to the fact that temp acts as a reference to shop.shopDetails. In JavaScript, objects are passed by reference, so when you set temp.receiptNumber, it essentially becomes shop.shopDetails.receiptNumber. Therefore, the value of temp in the subsequent iterations carries over from the prior iteration

To gain a better understanding of how JavaScript handles object variables, I recommend reading this insightful explanation.

In terms of resolving your issue, one approach is to clone the shop.shopDetails object in every iteration, ensuring that you receive a fresh object each time.

For example:

const shopList = [];
const shop = {
    "shopNumber": "2242461",
    "shopDate": "2020-06-13T00:00:00.000-05:00",
    "shopAmount": "100",
    "shopBank": "HDFC",
    "shopDetails": {
        "shopNumber": "1242461",
        "shopDate": "2020-06-13T00:00:00.000-05:00",
        "shopBank": "HDFC",
        "shopAmount": "100"
    },
    "receiptDetails": [{
        "userNumber": "115729",
        "receiptNumber": "temp1"
    },
    {
        "userNumber": "115726",
        "receiptNumber": "temp2"
    }]
};

shop.receiptDetails.forEach((receipt) => {
    var temp = {...shop.shopDetails}; // This method clones an object; there are alternative techniques available.
    temp.receiptNumber = receipt.receiptNumber;
    shopList.push({
        shopNumber: shop.shopNumber,
        userNumber: Number(receipt.userNumber),
        receiptNumber: receipt.receiptNumber,
        shopDetails: temp,
        isSync: 0
    });
});

shopList.forEach((receipt) => {
    console.log(receipt);
});

Answer №2

The issue with the duplicate receipt number arises from these two lines, where you are essentially duplicating the JSON object in the shopList. Only the last update is retained.

var temp = shop.shopDetails;
temp.receiptNumber = receipt.receiptNumber;

I suggest cloning the shopDetails and then adding the receiptNumber.

var temp = JSON.parse(JSON.stringify(shop.shopDetails));

Below is the revised code:

const shopList = [];
const shop = {
  "shopNumber": "2242461",
  "shopDate": "2020-06-13T00:00:00.000-05:00",
  "shopAmount": "100",
  "shopBank": "HDFC",
  "shopDetails": {
    "shopNumber": "1242461",
    "shopDate": "2020-06-13T00:00:00.000-05:00",
    "shopBank": "HDFC",
    "shopAmount": "100"
  },
  "receiptDetails": [{
    "userNumber": "115729",
    "receiptNumber": "temp1"
  },
  {
    "userNumber": "115726",
    "receiptNumber": "temp2"
  }
  ]

};
shop.receiptDetails.forEach((receipt) => {
  var temp = JSON.parse(JSON.stringify(shop.shopDetails));
  temp.receiptNumber = receipt.receiptNumber;
  shopList.push({
    shopNumber: shop.shopNumber,
    userNumber: Number(receipt.userNumber),
    receiptNumber: receipt.receiptNumber,
    shopDetails: temp,
    isSync: 0
  });
});
shopList.forEach((receipt) => {
  console.log(receipt);
});

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

Creating messages from an array using vanilla JavaScript or jQuery

I have an array of objects containing messages that I want to display on my webpage, but I'm unsure how to approach it. [{"message":"dwd","user":"csac","date":"07.04.2021 20:46"}, {"mes ...

Selecting the "pretty print" format for your Graph API request specifically

When using a specific browser to query the Graph API, the JSON output is nicely formatted for human readability. However, when using any other browser, the output is all on one line. Is there a way to make the request explicitly and avoid the formatting? ...

Scrollmagic - Creating dynamic effects by animating body and div backgrounds using multiple tweens

I'm currently developing a website that utilizes scrollmagic to smoothly transition the color of the active div (each set to size of the screen) from black back to white as you scroll down. The issue I am facing is that the body background color does ...

Is there a guarantee that XHR requests made within a click handler of an anchor tag will always be sent?

I'm trying to find information on whether an XHR request triggered in an anchor tag's click event handler is guaranteed to be sent. Despite my attempts at searching, I can't seem to locate a definitive answer. The specific question I have i ...

What is the reason behind Gson anticipating an array at the start but receiving an object instead?

I have encountered an error while using this JSON data to fetch articles with Retrofit: Received an error message: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 Below is the code I am working on: RestAdapter restAdapter = new RestAdapte ...

Decoding JSON Data in Angular 2

I am facing a challenge where I have an array of JSON objects that need to be parsed into my Tournament class. The Tournament class has the following structure: export class Tournament { constructor (public id: number, public name: string, ...

"Encountering a problem with object transformation in Three.js using

I'm attempting to adjust both the height (Y) and vertical position of a cube simultaneously in order to keep its base on the same X-Z plane after scaling. The visual display seems to be working correctly, but the actual behavior is not meeting my expe ...

Establish the editor's starting state

Currently, I am utilizing lexical and aiming to establish initial text for the editor. At the moment, my approach involves hardcoding the initial text, but it seems I cannot simply pass a String as anticipated. Instead, the format required is JSON. Hence ...

Verify the checkbox for validation is shown exclusively

I am currently facing an issue with a form that includes a checkbox, which is only displayed under certain conditions. I want to ensure that the checkbox is checked only when it is visible, and if not, the form should be submitted upon clicking the submit ...

What is the best way to bundle an Express server into an Electron application?

Currently in the process of developing an Electron app using vue-cli-electron-builder. My setup includes a local MySQL database and an Express server. I am wondering how to bundle my Express server with the Electron app? The Express server is used for d ...

Quasar Vue - Qselect component not populating with async data, showing [object Object] as default value

Within my created() method, I am making a call to Firestore to populate an array called ebscoCachedSearchesController in the data section. This array consists of objects that are correctly configured to be displayed in the qselect component. However, when ...

Navigating through each item in a JSON file with robotframework and extracting specific ones based on a query

I am currently working on extracting a specific node from a JSON file based on another node in the same element. To clarify, I need to retrieve the names of all students in the JSON sample provided below who are marked as "certified":"false". Sample JSON { ...

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

React component showcasing live data based on the URL's input

I'm looking to develop a dynamic component that can retrieve and display data from a JSON file based on the URL path, rather than creating separate pages for each dataset. For instance: https://jsonplaceholder.typicode.com/posts If the page route is ...

JavaScript node_modules import issue

I've been grappling with this issue for quite some time now. The problem lies in the malfunctioning of imports, and I cannot seem to pinpoint the exact reason behind it. Let me provide you with a few instances: In my index.html file, which is complet ...

The repeated execution of a Switch Statement

Once again, I find myself facing a puzzling problem... Despite making progress in my game, revisiting one aspect reveals a quirk. There's a check to verify if the player possesses potions, and if so, attempts to use it involves calculating whether the ...

JSON API Status Reversal

I've been trying to figure out how to check the current status of the PlayStation server. This information is typically displayed on their webpage which can be found here: Interestingly, instead of using PHP database queries, PlayStation seems to uti ...

Using Javascript to Swap the Content of an Element

Recently, I've been delving into the world of javascript and have hit a roadblock. I understand how to instruct javascript to set a specific value for an ID, but now I have a new challenge: I want to create javascript code that can retrieve informati ...

Zero values disappeared from the parameters in an Ajax request

When I send parameters for a WebMethod using Ajax, I receive an object. However, the parameters are losing zeros in the WebMethod. For example, if I send "00001234", on the backend the parameter is received as "1234". Here is the Ajax code that I am using ...

The best approach for setting a select value and managing state in React using TypeScript

Currently, I am in the process of familiarizing myself with TypeScript within my React projects. I have defined a type for the expected data structure (consisting of name and url). type PokedexType = { name: string; url: string; } The API respon ...