A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form

formKeyValues

https://i.stack.imgur.com/nRfiu.png

form

https://i.stack.imgur.com/eDpid.png

I am looking to extract only the keys and values from formKeyValues and place them in a new array called parameter - with keys corresponding to form.formKeys -

While attempting this, I encountered some issues.

this.formKeyValues=this.selectedTimeLine.formKeyValues;
this.parameter=[];
this.formKeyValues.forEach((para)=>{
  if(para.key==this.selectedTimeLine.form.formKeys){
    this.parameter.push('d[/data/'+this.selectedTimeLine.form.formId+'/'+para.key+']='+para.value);
  }
});

Answer №1

To determine if an element exists within an array, you can utilize the includes method. To create a new array based on specific criteria, employ the filter function. Lastly, to transform the resulting array into your desired structure, use the map method.

Consider implementing the following approach:

this.result = this.selectedData.entries
  .filter(entry => this.selectedData.set.keys.includes(entry.key))
  .map(entry => 'd[/data/'+this.selectedData.set.id+'/'+entry.key+']='+entry.value);

Answer №2

Here is a solution provided for you to review. The code snippet below contains a JavaScript solution that can be executed here. If needed, you can easily convert this code to Angular by replacing 'var' with 'const'.

const formKeyValues = [{
    key: 'key 1',
    value: 1
  },
  {
    key: 'key 2',
    value: 2
  },
  {
    key: 'key 3',
    value: 3
  },
  {
    key: 'key 4',
    value: 4
  },
  {
    key: 'key 5',
    value: 5
  },
];

const form = {
  formId: 1,
  formKeys: ['key 2', 'key 4', 'key 5']
};

const parameters = this.formKeyValues.filter(x => this.form.formKeys.indexOf(x.key) > -1).map(para => 'd[/data/'+this.form.formId+'/'+para.key+']='+para.value);
console.log(this.parameters);

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

Setting up a Typescript project with a shared package configuration

Before I begin, there are a few premises to consider: I require a shared package that will be included in three other packages, TypeScript, Only one node modules, Ability for multiplatform usage (Windows / Linux), To utilize dependencies from the shared ...

Encountering an ERROR during the compilation of ./src/polyfills.ts while running ng test - Angular 6. The module build

I encountered a problem in an angular project I am working on where the karma.config was missing. To resolve this, I manually added it and attempted to run the test using the command ng test. However, during the execution, an error message appeared: [./src ...

Error: The function createImageUrlBuilder from next_sanity__WEBPACK_IMPORTED_MODULE_0__ is not defined as a valid function

Having some trouble with my Next.js TypeScript project when integrating it with sanity.io. I keep getting an error saying that createImageUrlBuilder is not a function. See screenshot here Here is the code from my sanity module ...

Unable to play audio src in Angular 2 due to http request issue

The data I gathered and included in the audio source is not playing. component.detail.ts export class DetailComponent implements OnInit { @Input() detailName: string; @Output("playnhac") play = new EventEmitter(); private mp3Link:string; ...

Issue with MathJax rendering within an Angular5 Div that's being observed

I am trying to figure out how to enable MathJax to convert TeX to HTML for elements nested within my div. Here is the current content of app.component.html: <p> When \(a \ne\) It works baby </p> <div class="topnav"> ...

Implementing Angular Universal on Azure Platform

After converting my application to Angular Universal at the request of my clients, I successfully ran it using npm run serve:ssr and accessed it through http://localhost:4000. Now, the challenge lies in deploying it. Upon running npm run build:ssr, a dist ...

Issue with Typescript: For in loop not identifying object properties

Currently, I am utilizing a loop with for in to iterate through a list of Meeting objects named allMeetings. Inside this loop, I am populating another list called allEvents, where non-Meeting objects will be stored. However, when attempting to access the p ...

Is it possible to verify if a bearer token has expired within an Angular application?

Is there a secure and efficient way to determine when a bearer token has expired in my Angular application? This is the issue I am facing: If I keep the app open in my browser, someone could potentially access sensitive information on my screen since I am ...

Cross-site request forgery (CSRF) vulnerability spanning multiple applications

I am managing 2 separate applications under the same domain. One is hosted on a PHP 5.6 server with a Laravel 5.2 backend and an Angular2 frontend, while the other is on a PHP 5.3 server with a custom framework and a flat JavaScript frontend. Both applicat ...

Having trouble with downloading a zipped folder on the client side in an Angular and Node.js (MEAN) application

I am facing an issue with allowing users to download compressed folders from the server. I have successfully compressed the folder, however, when attempting to read the tar file and send it for download on the client side, the file is either corrupted or o ...

How to access the result without using subscribe in Angular?

I am facing unexpected behavior with a method in my component: private fetchExternalStyleSheet(outerHTML: string): string[] { let externalStyleSheetText: string; let match: RegExpExecArray; const matchedHrefs = []; while (match = this.hrefReg.exe ...

What options are available for customizing the date and time format within ngx-mat-datetime-picker?

Currently, I am working with Angular7 and the ngx-mat-datetime-picker which is compatible. It is functioning as intended. I am looking to customize the format: Current Format: mm/dd/yyyy, hh:mm:ss Desired Format: yyyy-mm-dd hh:mm:ss At the moment, I am ...

The noUnusedLocal rule in the Typescript tsconfig is not being followed as expected

I am currently working on a project that utilizes typescript 3.6.3. Within my main directory, I have a tsconfig.json file with the setting noUnusedLocals: true: { "compilerOptions": { "noUnusedLocals": true, "noUnusedParameters": true, }, ...

What are the steps for integrating Socket.IO into NUXT 3?

I am in search of a solution to integrate Socket.IO with my Nuxt 3 application. My requirement is for the Nuxt app and the Socket.IO server to operate on the same port, and for the Socket.IO server to automatically initiate as soon as the Nuxt app is ready ...

"Utilize the Image ID to Showcase Images in a MEAN Stack

I am currently working on saving an image in mongoDB and then retrieving it to display from the Angular side. profile.html <input class="file-hide" type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." /> <button type="b ...

Angular Signal computation does not initiate a re-render

I am currently working on sorting an array of signals within my component. To achieve this, I have wrapped the array in a compute function that sorts it. Below is the relevant code snippet: In the Service file: private readonly _lobbies = signal<Lobby ...

A different approach to showcasing components in SvelteKit based on the width of the screen

In my SvelteKit app, I'm using this code to retrieve the current window size and switch the displayed component when the width is small: <script> let size; </script> <svelte:window bind:innerwidth{size}/> <div> {#if size &g ...

"Conceal Digits with SweetAlert2's Number Mask

Could you assist me in adding a number mask to an input field in sweetalert2? Here is my code: onClick(btn) { let code2_fa = ''; if (JSON.parse(localStorage.getItem('user')).password.two_factors.is_active) { swal({ ...

The anticipated outcomes are not achieved when utilizing environmental variables in Angular 2

Is it expected that when we use ng serve --env=prod, it should work with the values set in environment.prod.ts? Well, in my experience, it doesn't seem to be working as expected as I always receive the values from environment.ts (which is the developm ...

Can the NgModule objects be imported from an external file?

One of my goals is to streamline the organization of my app by putting everything into logical files. I frequently do this in C#. Is there a way to extract declarations into a separate file and then assign the value to the declarations variable on NgModule ...