Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [
{ 
  id: 1,
  compId: 11,
  active: false, 
},
{ 
  id: 2,
  compId: 22,
  active: false, 
},
{ 
  id: 3,
  compId: 33,
  active: false, 
},
]

arrayTwo: [
{ 
  id: 1,
  compId: 11,
  active: true, 
},
{ 
  id: 2,
  compId: 33,
  active: false, 
},
]

I am presented with two JSON arrays and need to compare the compId keys in order to update the active key in arrayOne based on matching entries in arrayTwo.

In my attempt to solve this using AngularJs, I referred to a similar question on Stack Overflow which can be found here.

However, I now seek guidance on how to execute this comparison and update functionality in an Angular 6 project written in TypeScript.

The expected outcome should result in:

arrayOne: [
{ 
  id: 1,
  compId: 11,
  active: true, 
},
{ 
  id: 2,
  compId: 22,
  active: false, 
},
{ 
  id: 3,
  compId: 33,
  active: false, 
},
]

Answer №1

Give this a shot,

// Loop through the first list
for(let element of this.listOne){
    // Verify if the element is present in the second list
    if(this.listTwo.find(i=>i.compId==element.compId)){
        // Update the key value
        element.active = this.listTwo.find(i=>i.compId==element.compId).active;
    }
}

Answer №2

To implement the desired functionality, you can utilize the map and filter functions in the following manner:

listOne = listOne.map(item => {
       let matchingItem = listTwo.filter(c => c.compId == item.compId)[0];
       if(matchingItem != undefined){
           item.active = matchingItem.active;
           return item;
       }else{
           return item;
       }
    });

let listOne= [
{ 
  id: 1,
  compId: 11,
  active: false, 
},
{ 
  id: 2,
  compId: 22,
  active: false, 
},
{ 
  id: 3,
  compId: 33,
  active: false, 
},
]

let listTwo= [
{ 
  id: 1,
  compId: 11,
  active: true, 
},
{ 
  id: 2,
  compId: 33,
  active: false, 
},
]

//let arr3 = [];

listOne = listOne.map(item => {
   let exist = listTwo.filter(c => c.compId == item.compId)[0];
   if(exist != undefined){
       //item.id = exist.id;
       item.active = exist.active;
       return item;
   }else{
       return item;
   }
});

console.log(listOne);

Answer №3

After some trial and error, I was able to find a solution for the problem at hand. The approach involves iterating through two lists using nested for loops, checking each data point against one another and making necessary replacements.

for (const s of listOne) {
              for (const r of listTwo) {
                if (s.compId === r.compId) {
                  s.active = r.active;
                  break;
                }
              }
            }
  • Although I have provided a link to an answer related to AngularJS, please note that I am specifically looking for a solution in Angular 2+ with Typescript.

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

When trying to set the state in the OnMouseOver event, an error is thrown: TypeError - React is

Despite encountering numerous posts discussing this issue, I am struggling to resolve it in my particular scenario. I have a collection of items that I am attempting to apply color changes to (the div's) when they are hovered over. The coloring only ...

Implement a one-second delay before nesting another animation

I'm currently utilizing a timeout function, but I am interested in using a delay instead. My goal is to have the second animation start when one second has passed from the beginning of the first animation, and it should be a linear animation. How can ...

Using Phonegap alongside ons-scroller and ons-button

Recently, I have been using Phonegap with the Onsen UI system on iOS devices. I encountered an issue where buttons included within an ons-scroller were not clickable when running on an iPad or iPhone. Here is the code snippet that caused the problem: < ...

What is the best way to identify a specific list item from a dropdown menu and determine its position on

Check out my jsfiddle for reference. My goal is to calculate scores based on different options selected, specifically relating to radiation types. I'm struggling with assigning a score to each type of radiation and integrating the drop-down menu selec ...

Guide on creating a universal template from a collection of interfaces

Two interfaces, AllTypes type: interface A { // ... } interface B { // ... } type AllTypes = A | B; How can I utilize generics to ensure that a function's argument is an object with either interface A or B? // pseudocode function test<T ...

Only trigger NgRx actions when specific properties change during Rxjs Polling

I am working with a Rxjs Polling effect that looks like this: updateProductData$ = createEffect(() => this.actions$.pipe( ofType(fromActions.loadProduct), switchMap(_) => this.http.get('endpoint').pipe( delay(1000), ...

md-input-container malfunctioning

I am facing an issue with the code using "@angular/material": "^2.0.0-beta.1" import { MaterialModule, MdIconRegistry, OVERLAY_PROVIDERS, MdInputContainer, MdInputDirective } from '@angular/material' .... <md-input-container> <i ...

Limit file upload size to less than 1MB in Angular 2 with typescript using ng2-file-upload

Having issue with my code - I can't upload a file larger than 1mb even though maxFileSize is set to 50mb. Can anyone help me troubleshoot? @Component({ moduleId: module.id, selector: 'NeedAnalysisConsult', templateUrl: 'nee ...

JavaScript incorrectly constructs date strings

Hey there, I've been attempting to create a JavaScript date object using a string but for some reason, it's consistently off by one day. Every time I try, it ends up showing the wrong day. Below is the code snippet in question: var date = new Da ...

Adding typing to Firebase Functions handlers V2: A step-by-step guide

Here's a function I am currently working with: export async function onDeleteVideo(event: FirestoreEvent<QueryDocumentSnapshot, { uid: string }>): Promise<any> { if (!event) { return } const { disposables } = event.data.data() ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

Deploying an Angular 2 application using SystemJS and Gulp can sometimes feel cumbersome due to its

Although I have experience developing with Angular, I recently started working with Angular 2. After completing the quickstarter tutorial, I attempted to deploy the finished application on a server in production mode. My lack of experience with SystemJS a ...

How to Resolve jQuery Script Delay Caused by AJAX Request?

I am in the process of creating a unique responsive Wordpress Theme, with only one page that loads content via AJAX. Here is the AJAX function I have implemented: jQuery(document).ready(function(){ jQuery.ajaxSetup({cache:false}); jQuery(" ...

How do you display a nested object in React after merging it?

To display the JSON below as an image, click https://i.stack.imgur.com/tixu4.png let finalSplit = [ { start: "73", end: "76", splits: [ { word: "Now", start: "73", ...

Issue with Master Toggle functionality for checkbox within expanded rows of Mat-Table does not function correctly

I'm facing an issue with my multi-row expandable mat table grid where the master toggle for inner grid checkboxes is not working. Each row fetches data from different APIs on click, and I have a checkbox selection in every row for the inner grid. Int ...

Employ AJAX to dynamically refresh the page whenever a new row is inserted into the table

Currently, I am in the midst of learning AJAX because it is necessary for a project I am working on. The aim is to refresh a feed in real-time whenever a new row is added to a MYSQL table. While I have successfully achieved this using node.js, my client&ap ...

What steps do I need to take to incorporate dialog-polyfill into my React application?

Incorporating Firebase and FirebaseUI in my React application for phone number registration has been successful on Google Chrome desktop. However, when testing it on different browsers, such as through , I encountered an issue with the country code selecto ...

Retrieve data from the database and automatically populate all text fields when the dropdown value is modified

I need assistance with populating all textbox values based on the dropdown selection. The dropdown values are fetched using an SQL query. Here is the HTML Code: <select name="name" ID="name" class="form-control"> <opt ...

how to set a variable's value outside of a Promise using internal code

export class YoutubeService { getTrendingVideos(country) { let result = []; return axios.get('/').then(function(res){ result = res.data.items; for (var i = 0; i < result.length; i++) { result[i] = { id: ...

Is there a way to show a loading icon during the image change process without using jQuery?

How can I add a loading icon to an image change event without using jQuery? I'm new to the coding world and Stack Overflow community, so please bear with me. I've been searching for a solution to my specific situation but haven't been able ...