Changing the name of an object key dynamically in Angular 8

I need to dynamically change the name of factORLossTree to savefactORLossTree within the function in the payload below.

After submitting the form, I receive the following data in the payload.

{
    "cluster":"Europe",
    "factory":"Caivano",
    "factoryId":"Caivano",    
    "factORLossTree":[
       {
          "skuid":"000000000067334539",
          "skuDescription":"MAG 55ml Mini PistHazelnut 8MP x6x120 EB",         
          "levelLosses":[
             {
                "level1":"Line Scheduling Losses",
                "variancePer":100
             }
          ],
          "isRowChecked":false
       }
    ],
    "submitType":"po"
 }

The code snippet is as follows:

saveOrUpdateORData() { 
    const formData = Object.assign({}, this.orLosstreeForm.value);
    if (formData.factORLossTree.length === 0) {
      this.dialogService.openDialog('Data Not Available');
      return false;
    }  
    console.log(formData,"formdata");
    return;   
  }

Expected Output

{
    "cluster":"Europe",
    "factory":"Caivano",
    "factoryId":"Caivano",    
    "savefactORLossTree":[
       {
          "skuid":"000000000067334539",
          "skuDescription":"MAG 55ml Mini PistHazelnut 8MP x6x120 EB",         
          "levelLosses":[
             {
                "level1":"Line Scheduling Losses",
                "variancePer":100
             }
          ],
          "isRowChecked":false
       }
    ],
    "submitType":"po"
 }

Any help on how to achieve this would be greatly appreciated.

Answer №1

Of course! It's important to note that this particular issue is related to JavaScript and isn't tied to any specific framework like Angular.

Here's the solution in a nutshell: Let's assume your data is stored in a variable named payload

First, you check if the property exists. Then, you replace it with a new name:

const propertyName = 'enter the property name here'
const newPropertyName = 'enter the new property name here'

if (payload.hasOwnProperty(propertyName)) {
  payload[newPropertyName] = payload[propertyName]
  delete payload[propertyName]
}

Why does this work? By creating another reference to the original data before deleting the property, we ensure that one reference holds the updated name at the end.

If for some reason you need to clone the data instead, follow this approach:

if (payload.hasOwnProperty(propertyName)) {
  const clone = JSON.parse(JSON.stringify(payload[propertyName]))
  payload[newPropertyName] = clone
  delete payload[propertyName]
}

This assumes that the property always contains an object. If the property is of primitive type (such as number, string, or boolean), you can skip the cloning step altogether since primitives are copied by their values while objects are handled by their references.

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

Struggling to retrieve user input from a textfield using React framework

I'm having trouble retrieving input from a text-field in react and I can't figure out why. I've tried several solutions but none of them seem to be working. I even attempted to follow the instructions on https://reactjs.org/docs/refs-and-th ...

Encountering difficulties in running bootstrap on nodejs

As a beginner in node.js and bootstrap, I am eager to create my own personal website, so I found some tutorials to help me get started. After downloading bootstrap 2.0.2 and unzipping it, I organized the files by placing bootstrap and bootstrap-responsive ...

The Vue.js component was unable to retrieve the data

I am facing an issue with accessing data inside a simple component. Here is the code for my component: <template> <!-- success --> <div class="message-box message-box-success animated fadeIn" id="message-box-success"> <div cl ...

Refresh the homepage of a website using React Router by clicking on the site's logo from within the Home component

In most cases, when you click on a website's logo while on the homepage, it typically reloads the page. However, with React, clicking on the logo while already on the Home component does not trigger a reload. Is there a way to work around this issue? ...

What causes the intersection observer handler to not trigger when using scrollTo or scrollIntoView?

When an intersection observer is added to an element, it triggers the handler function when scrolled past a specific point. However, if the element is scrolled past that point using a button click, the handler does not get triggered. Is there a way to man ...

Utilizing Jcrop on an image loaded via ajax

Recently, I've been working on a project that involves uploading profile pictures to a server and storing them in a database using Ajax. While the basic functionality is working fine, I wanted to enhance the user experience by allowing users to crop t ...

Filtering a JSON response from a MySQL database using a REST API built with Node and Express - How can I limit the number of objects returned by passing parameters through the URL?

I am currently developing a REST API using Node, Express, and MySQL. When I want to request a list of Nodes from the http://localhost:3000/Node endpoint, I specifically want to limit the results to only 25 initial records. This can be achieved by making a ...

Issue Encountered in NodeJS While Processing Multiple GET Requests

I have been developing a web application that utilizes a database containing game data. When a user clicks on a game, a GET request is made to an API to retrieve additional information for the selected game. My goal is to ensure that users can access detai ...

Implementing multi-select checkbox feature in Angular 7 using ng-select

I'm looking to create a function where selecting an item will make the corresponding div appear. For instance, if I choose Crédit bancaire and Compte courant associé, the two corresponding divs should be shown. Check out this example: https://stac ...

Discovering the most efficient route between two locations within a grid of values

I'm currently working on a game where I need to find the shortest route between two points. https://i.sstatic.net/jBnEd.png In my map, I have a 2D array called matrix: Node[][], class Node{ index: { x: number, y: number }, isAvai ...

Enhance ng-grid with row expansion and collapse feature

I am looking to create a feature in ng-grid that allows for expanding and collapsing rows, similar to what is demonstrated here http://datatables.net/examples/api/row_details.html. If you click the "plus icon," more details are revealed. I found a related ...

The Challenge of the Universe's Origin

While watching the latest episode of The Big Bang Theory (Season 11, Episode 20), I found myself intrigued by Dr. Wolcott's unusual encryption method. In a quirky twist, this nutty theoretical cosmologist wrote his notes backward and converted all let ...

Encountering a puzzling issue with React JS and Redux, where using fetch consistently

I want to make an API request without using ajax call, as importing the whole library for just that seems unnecessary. Instead, I decided to follow the fetch function approach outlined in the Redux documentation (which I recently migrated with). import f ...

Encountering a SyntaxError with Angular (8) Http.post() due to an Unexpected token O in JSON at position 0 when trying to parse the

Whenever I attempt to send data to my server, an error is being returned: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse... Since I'm not utilizing JSON.parse(), could it be that Angular's Http.post() function is automatica ...

The S3 signature verification failed while generating a signed URL on the server-side using Node.js

Trying to upload a video file to my bucket using a pre-signed URL in angular4. Instructions: let s3 = new AWS.S3(); s3.config.update({ accessKeyId: process.env.VIDEO_ACCESS_KEY, secretAccessKey: process.env.VIDEO_SECRET_KEY }) ...

Utilize typehead.js in Python Django to retrieve an updated data list directly from the database

file.js var source = new Bloodhound({ hint: false, datumTokenizer: Bloodhound.tokenizers.obj.whitespace("description"), queryTokenizer: Bloodhound.tokenizers.whitespace, // /a_c/p_s/?term=d&category=all remote: "/a ...

Convergence phenomenon in SVG when two distinct paths intersect

Working with individual SVG paths and in need of a mitre effect when there is a path join, which is a new concept for me. The SVG shape resembles a polygon, with each side as its own individual path. Although the sample SVG code provided does not display ...

Implement a sleek carousel within a Vue component

Hello, I am trying to add a single slick carousel component to a block that already contains 2 components in a template. However, when I do this, it distorts the images of the other component. <template v-if="isMobile"> <vue-slic ...

Ways to verify if an array contains elements from other arrays in Typescript

How can I verify if the winningConditions are present in chosenNumbers? The chosenNumbers array is of varying lengths and consists of a mix of numbers. For example, one of the winning conditions is [0, 3, 6], but there is also the number 2 included. How ...