The Array Map method in JavaScript transforms each element within the array

I have a vector of objects in JavaScript (React Native) and I am trying to assign a unique random key to each item in the array. However, when I add the key property to one object, it ends up being the same for every element in the array.

It's puzzling me as to why this issue is occurring.

The original array looks like this:

[{"nome":"insalata di mare","prezzo":0.3,"qr_code":"qr_valore","quantita":3},{"nome":"insalata di mare","prezzo":0.3,"qr_code":"qr_valore","quantita":3}]

The resulting array is as follows:

Random product list: [{"nome":"insalata di mare","prezzo":0.3,"qr_code":"qr_valore","quantita":3,"key":"x4idec"},{"nome":"insalata di mare","prezzo":0.3,"qr_code":"qr_valore","quantita":3,"key":"x4idec"}]

This issue seems to occur only when the items are identical.

componentWillMount(){

    this.props.productList.map(item => {
      item.key = Math.random().toString(36).substring(7)
    })

}

The desired outcome should be a different key assigned to each object, something like this:

Random product list: [{"nome":"insalata di mare","prezzo":0.3,"qr_code":"qr_valore","quantita":3,"key":"x4idec"},{"nome":"insalata di mare","prezzo":0.3,"qr_code":"qr_valore","quantita":3,"key":"d2jdss"}]

Answer №1

Have you confirmed that each item in the array is actually a unique object?

Consider this scenario:

let a = {foo: 'bar'};
let b = a;
let array = [a, b];

In this case, the array will contain:

[{foo: 'bar'}, {foo: 'bar'}]

If you use the map method as demonstrated above, both items will change simultaneously because they are referencing the same object. This means that the changes affect all instances of that object within the array.

array.map((item, index) => item.key = index)

Will output:

[{foo: 'bar', key: 1}, {foo: 'bar', key: 1}]

Rather than

[{foo: 'bar', key: 0}, {foo: 'bar', key: 1}]
, which may have been your intended result.

To ensure that each element in the array can be modified independently, it is essential to guarantee that each item is a distinct object. Utilizing tools like lodash's clone function can aid in achieving this.

array.map((item, index) => _.clone(item).key = index)

Answer №2

Expanding on the points made by @kshetline.

I am of the opinion that this solution meets your requirements without relying on an external library.

const updatedProducts = this.props.productsList.map((product, index) => ({
  ...product,
  key: index
}));

One important thing to note is that a new object will be generated in this process, potentially overwriting any existing 'key' property!

Please share your thoughts on this approach!

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

What is the best way to render geoJSON as a mesh instead of a line in three.js, and apply a color fill to it?

Currently working on a three.js globe project that involves adding data layers using geoJSON. The initial layer, representing countries, is displayed as lines thanks to ThreeGeoJSON. https://i.sstatic.net/nuBkR.png However, I am aiming to go beyond just ...

Ways to show alternative data from a database in Laravel 8

I am working on a project where I need to display additional data based on the option selected from a dropdown menu populated from a database. Can anyone guide me on how to achieve this using javascript or jquery? https://i.stack.imgur.com/k3WLl.png Belo ...

What is the process behind __doPostback generating a URL on an ASP.NET website?

Can you please check out the following URL: When you select "Exhibitor A to Z" from the dropdown menu and click search, a javascript function is triggered for each link (javascript:__doPostBack('ctl00$MainContent$grdExhList$ctl00$ctl04$lnkExhLink&ap ...

Ways to Determine the Height and Width of an Image Once it has been Adjusted for a View

Is there a way to retrieve the height and width of an image after it has been resized for a view? I have images that may vary in original dimensions, but users can resize them as needed. For example, this code from the console gives the client height: do ...

What causes the scrollbar to move while I am dragging the div downward on the page?

$('#aaa').draggable(); * { margin: 0; padding: 0; } #aaa { width: 800px; height: 800px; position: absolute; background: red; } .wrap { height: 2000px; position: relative; ; } <div class="wrap"> < ...

Refresh ng-repeat array after implementing filter in controller

I am currently facing an issue with updating my table view when changing a variable that filters an array. The filter is applied in the controller based on the values of a specific variable called columnFilter. However, the filter does not reapply to updat ...

Extracting sound information from an ALSA buffer and converting it into a numpy array

I am currently working on extracting data from an ALSA buffer to create noise counts using a microphone. However, I am encountering issues when trying to convert the data into an array as it is returning incorrect results. Below you will find a snippet of ...

Executing numerous queries in mongoDB

I need to query multiple collections in MongoDB. Here is an example of the data structure: Collection stops { { stop_id : 1, stop_name: 'a'}, { stop_id : 2, stop_name: 'b'}, ... Collection stop_time { { stop_id : 1, trip_i ...

Middleware that is commonly used by both error handling and regular request-response chains

I am currently working on implementing a middleware that can set a variable in the sequence of both error and non-error scenarios. Is there a way to achieve this without disrupting the normal flow of middleware? Specifically, when I include the err param ...

Why is a <script> tag placed within a <noscript> tag?

Lately, I've been exploring various websites with unique designs and content by inspecting their source code. One site that caught my attention was Squarespace, which had blocks of <script> tags within a <noscript> tag: <!-- Page is at ...

What is the best way to extract information from these JSON values?

My goal is to retrieve JSON values from a specific object. Here is the structure of this JSON data: { "attrs": { "width": 1728, "height": 787, "dragabble": true }, "className&qu ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

Return to a mention of a tree reference

Here is an example code snippet: <table> <tr> <td></td> <td></td> <td> <table> <tr> <td><a href="#" class="fav">click me</a></td> ...

Capture data from ajax effectively by extracting and executing manipulations seamlessly

I have a project where I need to retrieve images from a database using Ajax and display them using a carousel plugin. This is the process: An image URL is saved to the database by an admin The frontend script makes an Ajax call to a PHP file and retrieve ...

Issues with executing basic unit test in Angular Js

THE ISSUE: In an attempt to create unit tests for my Angular application, I set up a basic test app and wrote a simple unit test. However, the test is not functioning as expected. APPLICATION CODE: var app = angular.module( 'myApp', [] ); app ...

php encode mysql results in a custom JSON format

Currently, I am using json encoding to format the result of a MySQL query in a PHP file. Here is my current PHP script: while ($row = mysql_fetch_array($result)) { $to_encode[] = $row; } echo json_encode($to_encode); Current Output [ { "0": "Va ...

Constrained script function

My main query is how can I trigger a button click event in javascript. I am aware of using document.getElementById("btnSubmit").click();, but it does not seem to execute the onClientClick javascript function as well. Environment: I am working with ASP.N ...

What is the best way to safely distribute the same npm package with multiple contributors?

Imagine a collaborative open source project with multiple contributors working on it. As the project progresses, these contributors need to publish their work to the NPM registry. But how can this be done securely when multiple people are involved? The ow ...

Merging Two Arrays to Form a Single Array in React

Let's consider the following arrays: const headerArray = ["h1","h2","h3"]; const dataArray=[["a1","a2","a3"],["b1","b2","b3"]]; I have a requirement to merge th ...

How can I update my outdated manifest v2 code to manifest v3 for my Google Chrome Extension?

Currently, I am developing an extension and using a template from a previous YouTube video that is based on manifest v2. However, I am implementing manifest v3 in my extension. Can anyone guide me on how to update this specific piece of code? "backgro ...