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

Using TypeScript to set an HTMLElement in a web page

Currently in the process of transitioning my old JavaScript code to TypeScript. One of the components I have is a Table Of Contents JSX component that helps me navigate easily to specific headings. I had a function that calculated the total offset needed ...

Ways to boost the efficiency of your Ionic 4 app development process

I have created an Ionic 4 app with over 50 screens, including components and popups. The build and live reload process is taking a lot of time, especially for minor UI changes. Is there a way to speed up the development process? Here are my Environment Se ...

What steps can be taken to resolve the issue of receiving the error message "Invalid 'code' in request" from Discord OAuth2?

I'm in the process of developing an authentication application, but I keep encountering the error message Invalid "code" in request when attempting to obtain a refresh token from the code provided by Discord. Below is a snippet of my reques ...

When using routerLink, it automatically converts the URL to a

I am currently working on an Angular project where I need to link to bookmarks on other pages. In my HTML, I have links structured like this: <a href="#products" routerLink="overview">products</a> However, during compilation and execution of ...

Combine two arrays of data sources

mergeThreads() { const userId = this.auth.getUser().uid; const buyerThreads$ = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges(); const sellerThreads$ = this.afs.collection ...

A guide to finding the mean in Angular by utilizing JSON information

import { Component, OnInit } from "@angular/core"; import { MarkService } from "../app/services/marks.service"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComp ...

typescript - add a global library import statement to every script

Recently, I began working on a TypeScript project in Node.js. I am looking to add import 'source-map-support/register'; to all of my .ts files for better visibility of TS source in stack traces. Is there a method to implement this without manuall ...

What are some strategies for distinguishing between callable and newable types?

I seem to be facing a challenge related to narrowing, specifically the differentiation between Fnc (callable) and Class (newable). The code snippet provided functions in Playground, but the autocomplete feature is lacking, as shown in the first image. My ...

TS2688 Error: Type definition file for 'keyv' is missing

The automated code build process failed last night, even though I did not make any changes related to NPM libraries. The error message I received was: ERROR TS2688: Cannot find type definition file for 'keyv'. The file is in the program because: ...

Is there Polyfill Compatibility for Custom Elements in Angular 9?

When it comes to polyfilling support for custom elements created with Angular, there are various recommendations available. This demo demonstrates that adding the following polyfill in polyfills.ts works: import '@webcomponents/webcomponentsjs/custo ...

What is the best way to pass the username and token data from a child component to its parent component

Hey, I'm currently working on a login app in React where the login component is a child of the app. My goal is to send back the username and token to the parent component once a user is logged in, so that I can then pass this information to other chil ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

Using Typescript to overload functions with varying first parameters

I am facing a scenario where I have a parent class that requires a method implementation with either one or two parameters depending on the child class. class MyClass { update(obj: HashMap); update(id: ID, obj: HashMap); update(objOrId: HashM ...

Using type values in TypeScript

I am trying to assign interfaces as values within a config object: export interface RouterConfig { startEvents?: typeof RouterEvent[]; completeEvents?: typeof RouterEvent[]; } The intended usage is as follows: private config: RouterConfig = { star ...

Error Alert: The system is unable to locate property 'next' in Angular/Jasmine

Whenever I utilize the service below in a component, an error message "TypeError: Cannot read property 'next' of undefined" pops up and previously functioning tests start failing as well. The Service: export class DataService { loadData$: ...

Problems with installing ambient typings

I'm having trouble installing some ambient typings on my machine. After upgrading node, it seems like the typings are no longer being found in the dt location. Here is the error message I am encountering: ~/w/r/c/src (master ⚡☡) typings search mo ...

Steps to obtain the download URL from AngularFireStorage after uploading the file using the getDownloadUrl() method

After successfully uploading images into my firebase storage, I want to retrieve the downloadURL and add it to my firestore database. When console logging "url", I am able to see the desired link. However, I am facing difficulties in using it. When attemp ...

Sending an ArrayBuffer from Angular to Electron results in the window crashing

In my Electron application, I have integrated an Angular application internally. I am trying to download a byte array (ArrayBuffer) via an API call and then passing this data to a method connected through electron.remote.require('./file-service') ...

Is it possible in TypeScript to change a string literal type into a number type?

Would it be feasible to develop a utility type Number<T> that can take a string literal type and convert it into a number? If conversion is not possible, should the utility return a never type? type Five = Number<'5'> // `Five` is con ...

Troubleshooting the error of an undefined RouterModule

Working on implementing lazy loading for my Angular 4 application, I have a total of 18 lazy loaded modules. Upon noticing that fetching these modules is taking some time, I decided to add a loading indicator. Everything worked fine when I added it locally ...