Assign updated values to a list based on changed fields in the map

In order to track the modified fields and display them to the user, I need to identify which key corresponds to the changed field and create a new key-value pair for user visibility.

log: [
    0: {type: "Changed", fields_changed: Array(2), date_modification: Timestamp, modified_by: "ID_USER"}
    1: {type: "Changed", fields_changed: Array(4), date_modification: Timestamp, modified_by: "ID_USER"}
    2: {type: "Changed", fields_changed: Array(2), date_modification: Timestamp, modified_by: "ID_USER"}
    3: {type: "Changed", fields_changed: Array(4), date_modification: Timestamp, modified_by: "ID_USER"}
]

fields_changed: [
    0: {key: "name", value: "New name"}
    1: {key: "age", value: 22}
]

To achieve this, I will use fieldsNames to match the field names and generate an updated log object for user viewing.

const fieldsNames = [
    {key: 'name', field_name: 'Name'},
    {key: 'age', field_name: 'Age'},
]

This process will result in a revised log list where field keys are replaced with corresponding field names.

Example:

fields_changed: [
    0: {key: "name", value: "New name", field_name: "Nome"}
    1: {key: "age", value: 22, field_name: "Age"}
]

A new key called field_name will be added within each object of the fields_changed list to indicate the name of the modified field that can be shown to the user.

This method ensures that the fields_changed list is updated as illustrated above.

For user clarity on the changes made, I plan to iterate through fields_changed and extract the associated field_name string representing the field name.

Answer №1

Alright,

If I got your message correctly, this solution should be beneficial for you. It generates a new log object with an array called fields_changed that holds objects like

{key: string, field_name: string, value: string,}
.

Below is a practical example where I made some adjustments to your initial code for clarity.

const log = [
    {
        type: "Modified", 
        fields_changed: [
            { key: "name", value: "New name" },
            { key: 'city', value: 'New York' }
        ]
    },
    { 
        type: "Modified", 
        fields_changed: [
            { key: "age", value: '10' }
        ] 
    },
]

const fieldsNames = [
    { key: 'name', field_name: 'Name' },
    { key: 'age', field_name: 'Age' },
    { key: 'city', field_name: 'City' }
]


const changes_for_display = log
    // iterate through each entry in the log.
    .map(change => ({

        // map the fields_changed property for each object,
        fields_changed: change.fields_changed.map(field_change => {

            // Find a matching field in fieldsNames based on the key from field_change.
            const field = fieldsNames.find(name => name.key === field_change.key);
            if (!field) {
                throw 'Error: Field ' + field_change.key + ' NOT FOUND....';
            }

            // create a new field_change object by assigning the value property from the matched field,
            return Object.assign(field, { value: field_change.value })

        }), type: change.type })
    );


// That's all for now!
console.log(changes_for_display)

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

Utilizing a single AWS IoT connection for every component in Angular 6: A complete guide

In my Angular 6 project, I integrated AWS IoT for chat and notification functionalities. Initially, I was connecting to AWS IoT from multiple components like the header, chat, and home components. However, I now want to streamline the process by establishi ...

Stack the labels of separate datasets on top of each bar in a bar chart using Chartjs: How can this be achieved?

chart.js 4.4.2 chartjs-plugin-datalabels I am aiming to achieve this effect const chartCtr = document.querySelector('#temp-chart1') as HTMLCanvasElement; new Chart(chartCtr, { type: 'line', plugins: [ChartDataLabels], opt ...

Having trouble setting the InnerHTML property of Null on my Ionic app, what could be the issue?

I'm working on a code to display the remaining time for generating a random code in the DOM. var count = setInterval(function () { var date = new Date(); var currentSecond = date.getSeconds(); ...

Ensuring Type Safety for Collections in TypeScript

My code snippet looks like this: portfolioList: MatTableDataSource<Portfolio>; ngOnInit(): void { this.backend.getStatement().subscribe( list => { if(list as Portfolio[]) this.portfolioList = new MatTableDataSource(l ...

How come my bubble sort algorithm isn't functioning properly with double data types?

Currently, I am attempting to implement a function that uses bubble sort to sort an array. The version I created for an integer array appears to be functioning correctly. However, the version for a double array is not producing the desired outcome (it retu ...

Exploding a key value pair and grouping matching key values into one key - here's how to do it!

I have encountered a practical issue recently while working on ajax form submission. There are checkboxes involved and I need all checkboxes with the same name to be stored as key value pairs. For example, if there are 4 checkboxes with the name attribute ...

The Elusive Glitch: IOS Encounter with Ionic 2

VIEW PROBLEM</p> I am currently developing an Ionic 2 application using Angular 2. Interestingly, I have encountered a peculiar issue that only occurs on one specific page of the app, but specifically on IOS devices. Strangely enough, only the visib ...

Can you explain the use of parentheses in a typescript type when defining a key?

Could someone provide an instance of an object that matches the TypeScript type below? I'm a bit confused because I've only worked with interfaces before and have only seen square brackets. type Hash = { (data: Uint8Array): Uint8Array blockLe ...

Angular Service Worker: 504 error encountered during application deployment refresh

After building my Angular 8 project with ng build --prod, I serve it from the /dist folder using http-server. The app still works even after stopping it thanks to the service worker. The project successfully registers its service worker and I am able to ...

Troubleshooting ngFor in Angular 5

I'm currently working on a component that needs to display data fetched from the server. export class CommerceComponent implements OnInit { dealList; ngOnInit() { this.getDeals(); } getDeals(){ this.gatewayService.se ...

AWS Lambda Layer - Typescript - Error Importing Module Runtime

Hello there! I'm currently facing an issue with implementing lambda layers on a lambda function that I've set up. I've tried numerous approaches to get it right, but nothing seems to be working. Based on my research, this seems to be a comm ...

Determining the accurate object from a nested type in Typescript is essential

I'm currently facing a challenge with Typescript in inferring the correct object within a switch case. I find it puzzling why my scenario works as expected with a union type but not with an object. Here is the code from the playground link: interface ...

Is it possible to utilize the NX CLI for managing both Angular and React applications within the same Nx workspace?

When attempting to set up my workspace, I encountered some errors. To start, I created an Nx workspace by running: npx create-nx-workspace@latest myworkspace, and then chose Angular CLI as the option. Next, I generated an Angular app using the command: y ...

The syntax for Python arrays

Perhaps this question may seem silly or easy, but I'm unsure how to interpret this type of array notation in Python. self.sessions[(recepientId, deviceId)] I am attempting to convert some Python code to PHP. Although someone mentioned it is unclear ...

Combining multidimensional arrays in PHP

I have been pondering about how to merge two multidimensional arrays together. While I have come across similar solutions, they don't quite match what I am aiming for. Perhaps one of you could lend me a hand. Yes, I understand that the title is somewh ...

A C# program that creates an array collater where the value of every other element is the same throughout the

I'm currently exploring an extension of my project, looking for a more concise solution. While it's easy to achieve this in a loop, I am curious if there is a way to do it in just one line of code. Here is the initial input: byte[] x = new byte ...

"Exploring the world of arrays and looping in

Can someone assist me with this issue? I am currently stuck in JS Arrays & Loops and I can't understand why it's not returning "0" when the function is empty. function sumArray (numbers) { // your code var numbers = [1, 2, 3, 4]; if (nu ...

Do you need to finish the Subject when implementing the takeUntil approach to unsubscribing from Observables?

In order to prevent memory leaks in my Angular application, I make sure to unsubscribe from Observables using the following established pattern: unsubscribe = new Subject(); ngOnInit() { this.myService.getStuff() .pipe(takeUntil(this.unsubscr ...

Angular HTTP post call is failing to redirect to the correct URL

https://i.sstatic.net/CzSuQ.pngCan someone assist me in resolving the http post problem? I am facing an issue where the url validation is not working correctly. Even when localhost:8084 is up and running, the error section is triggered, and the same happen ...

Sending JSON Object using NavController

I am trying to send a JSON Object to another Page in my Ionic 2 application. However, when I attempt to do so, I encounter the error: Cannot read property 'user' of undefined. While researching for a solution, I came across a similar question ...