Manipulate the elements within an array, make changes, and then insert

In the array called newData, I am trying to add one more element with Rank 1. However, the issue is that the Rank value is getting updated for both records. The desired behavior is to have Rank set to 1 for the second record and have the first record's Rank as null.

I need help identifying what mistake I might be making in the following code.

let newData = [{
    "key1": {
        "cc":'IND'   
    },          
    "key2": {
        "rank": null
    }
}];

let setData = newData.concat(newData.slice());

setData.forEach(data => { 
    data.key2.rank =+ 1;
});

Answer №1

One possible solution is as follows:

let newData = [{"key1": {"cc":'IND' }, "key2": {"rank": null}}];

    // To combine arrays, use the spread operator and you can leverage map instead of slice
    let setData = [...newData, ...newData.map(data => { 
        /* Objects are passed by reference, so you must break the reference
         * to create a clone of the object. */
        data = JSON.parse(JSON.stringify(data));
        data.key2.rank =+ 1; 
        return data;
    })];

console.log(setData);

Answer №2

setData.forEach(data => { 
  data.key2.rank += 1;
});

Consider changing the operator from =+ to +=

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

Prevent Repeated Data Input in an Array using JavaScript

I am facing an issue where I need to ensure that the values being inserted are not repeated when performing a push operation. Below is the snippet of code in question: addAddress: function() { this.insertAddresses.Address = this.address_addres ...

Puppeteer - Issue with Opening Calendar Widget

Problem: Unable to interact with the calendar widget on a hotel website (). Error Message: Node is either not clickable or not an Element Steps Taken (code snippet below): const puppeteer = require('puppeteer') const fs = require('fs/promi ...

What is the best way to locate and access a JSON file that is relative to the module I am currently working

I am in the process of creating a package named PackageA, which includes a function called parseJson. This function is designed to accept a file path pointing to a JSON file that needs to be parsed. Now, in another package - PackageB, I would like to invok ...

How can you specify the environment in Google Tag Manager?

I have integrated google tag manager and google analytics using the vue-gtm plugin found at vue-gtm Within google tag manager, I have set up 3 environments under the same container. In a user-defined variable called GA from environment, I have created a ...

Output various strings to the standard output and stream them individually

Is there a way to redirect each string output to standard out to another command? // Example file: example.js #!/usr/bin/env node process.stdout.write('foo') process.stdout.write('bar') After running ./example.js | wc -m, the total ch ...

Crushing jQuery's Sortable/Droppable

Having a little issue here. I want to be able to toggle the sortable plugin's behavior by clicking a button - basically switching between sort mode and view mode. I've attempted to achieve this with the following code: function enterSortMode(){ ...

Using TypeScript to chain observables in a service and then subscribing to them in the component at the end

Working with Platform - Angualar 2 + TypeScript + angularFire2 Within my user.service.ts file, I have implemented the following code to initiate an initial request to a firebase endpoint in order to fetch some path information. Subsequently, I aim to util ...

"Learn how to transfer a selected value from a parent ASP.NET dropdownlist to a textbox in a popup window using JavaScript

I'm struggling to pass the value from a dropdown list in the parent ASPX form to a textbox in the child ASPX form. Parent JavaScript: The first script is used to open the popup window <script type="text/javascript"> var popup; ...

An issue arises when attempting to utilize v-model with a file input

Is there a way to reset a file input field in Vue.js after uploading a file? I attempted to set the v-model value to null, but encountered an error message that said: File inputs are read only. Use a v-on:change listener instead. This is my current cod ...

The background size cover feature is not functioning properly on mobile devices, especially on longer pages

In my Next.js project, I am encountering an issue with the background image not displaying on longer pages when viewed on a Google Pixel 3a device. Here is how it looks on shorter pages that do not exceed the viewport height: https://i.sstatic.net/jJBTy.pn ...

Storing a reference globally in React and Typescript: Best practices

In my application, I have multiple instances of a specific component called <Item>. Each <Item> needs to display a dynamic tooltip when hovered over. To achieve this, I am utilizing semantic-ui-react and its Popup component. The conventional m ...

Obtain the VW/VH coordinates from an onclick action in JavaScript

With this code snippet, you'll be able to retrieve the x and y coordinates of a click in pixels: document.getElementById("game").addEventListener("click", function(event) { console.log(event.clientX, event.clientY); }); However ...

View complex response objects in Postman as easily digestible tables

I am interested in displaying the data provided below as a table using Postman Tests. The table should have columns for product, price, and quantity, with Items listed in rows. It's important to note that there may be multiple shippingGroups within th ...

Angular HTTP Patch method requires explicitly defined HTTP options as input parameters

I encountered a challenge with using Angular's HTTP patch method and noticed that the overloaded function patch(url, body, options) only accepts hardcoded values for HTTP options. An example of a hardcoded approach that works: patchEntity(id: number) ...

Transferring functionality from a child component to a parent component

I have a Base Component called ListComponent and a ParentComponent named Businesses2ListComponent. The concept is to have multiple types of Lists with tables that all stem from the ListComponent. This requires passing the correct service accordingly. In t ...

Retrieve tag, custom taxonomy, and attachment information using the get_pages function

Currently, I have implemented code that retrieves all pages submitted by the currently logged-in author using the get_pages function. The retrieved result is then passed to Javascript via Ajax. Everything functions as expected, and the correct pages are be ...

Angular Alert: [$injector:modulerr] Unable to create the angularCharts module because: Error: [$injector:nomod]

Although this question has been asked multiple times, the standard solutions provided did not resolve my issue. Therefore, I am sharing my code along with the error in hopes that it will be self-explanatory. Error: Uncaught Error: [$injector:modulerr] Fa ...

The HTML5 camera feature remains active even after navigating to a different page in an AngularJS application

I am currently exploring the video capabilities of HTML5. Using a directive userMedia, I have successfully activated my camera on my MacBook through navigator.getUserMedia() (using an adapter for cross-browser compatibility with supported browsers). Howev ...

What are some solutions for troubleshooting setInterval issues?

I have a h1 element with a v-for loop that displays items from my array in the following format: <h1 v-for="(record, index) of filteredRecords" :key="index" :record="record" :class="get ...

Unable to resolve the issue of Duplicate keys detected with value '0'. This could potentially lead to errors during updates

Encountered a warning in Vue js stating 'Duplicate keys detected: '0'. This warning could potentially lead to an update error. To resolve this issue, I utilized the getter and setter in the computed variable and dispatched the value to Vuex ...