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

Modifying the 'child' node within a JSON object

Exploring the implementation of d3s Collapsible tree using a custom node hierarchy. My dataset structure deviates from the norm, for example: http://jsfiddle.net/Nszmg/2/ var flare = { "Name": "Example", "members": [ { "BName":"Ja", ...

Tips for displaying the data on top of individual column bars: Hightcharts, Vue-chartkick, and Cube Js

Looking for assistance with adding value labels to the top of each column bar in a Vue chart using chartkick and highcharts. Check out the image above to see my current output. <template> <column-chart lable="value" :min="0" :refresh="60" he ...

Selenium's WebDriver getAttribute function can return an object of type "object",

In my selenium script, I aim to extract text from table columns following the cell with the specified value. Although the script functions, I encounter an issue where getText() returns [Object Object] in my node.js console. I have attempted various method ...

Display time series data from PHP by utilizing Flot Charts in jQuery

After receiving data from a database, which is formatted using PHP and returned as a JSON response for an Ajax call, I encountered an issue. Everything works fine and the data is plotted except when the X-Axis contains dates, in which case nothing gets plo ...

Using jQuery's $.ajax() function to make an asynchronous request, and then passing the

I'm currently utilizing the jQuery $.ajax() function within a parent function that passes values into the ajax call. I am looking to have a custom callback function that can access the data parameter returned from the success function of the ajax call ...

Escaping back slashes in Node.js

I am currently encountering an issue with escaping backslashes. Below is the code snippet that I have attempted. The problem lies in how to assign a variable containing an escaped slash to another variable. var s = 'domain\\username'; ...

Ways to extend the default timeout duration in Angular

My server calls are taking a long time, around 30-40 minutes, and my Angular frontend is timing out. Is there a way to increase the default timeout for this service call? method1(id: number): Promise<number> { const body= JSON.stringify(id); ...

Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object: Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1= ...

Changing the entire content of a webpage from the server using AJAX

I am looking to update the entire page content with the click of a button, transitioning from Words.html to SelectNumber.html This snippet is from Words.html <html> <head> <meta charset="UTF-8"> <title>Number Game< ...

Customize the appearance of radio buttons in HTML by removing the bullets

Is there a way for a specific form component to function as radio buttons, with only one option selectable at a time, without displaying the actual radio bullets? I am looking for alternative presentation methods like highlighting the selected option or ...

Expand the scope of the javascript in your web application to cater

I am in the process of creating a web application that utilizes its own API to display content, and it is done through JavaScript using AJAX. In the past, when working with server-side processing (PHP), I used gettext for translation. However, I am now ...

typescript - specifying the default value for a new class instance

Is there a way to set default values for properties in TypeScript? For example, let's say we have the following class: class Person { name: string age: number constructor(name, age){ this.name = name this.age = age } } We want to ens ...

React modal not triggered on click event

As a newcomer to react, I am exploring a modal component import React, { useState, useEffect } from 'react'; import { Modal, Button } from "react-bootstrap"; function TaskModal(props) { return ( <Modal show={pro ...

Utilizing TypeScript to export a class constructor as a named function

Imagine you have this custom class: export class PerformActionClass<TEntity> { constructor(entity: TEntity) { } } You can use it in your code like this: new PerformActionClass<Person>(myPersonObject); However, you may want a more co ...

Explore the full range of events available on the Angular UI-Calendar, the innovative directive designed for Arshaw FullCalendar

Utilizing external events with Angular ui-calendar: HTML: <div id='external-events'> <ul> <li class='fc-event'>Event 1</li> <li class='fc-event'>Event 2< ...

Type returned by a React component

I am currently using a basic context provider export function CustomStepsProvider ({ children, ...props }: React.PropsWithChildren<CustomStepsProps>) => { return <Steps.Provider value={props}> {typeof children === 'function&ap ...

Displaying an array using Javascript that contains variables along with HTML code

First of all, thank you for your help and support! I am struggling with correctly outputting HTML code with variables using jQuery and jQuery Mobile. I receive results from a PHP database, separated by "," and converted into a JavaScript array successfull ...

Feature exclusively displays malfunctioning image URLs for the web browser

Hello everyone! I've been diving into learning JavaScript and recently attempted to create a function that randomly selects an image from an array and displays it on the browser. Unfortunately, despite my efforts, all I see are broken link images. Her ...

The Google Cloud storage public URL access permission has been denied

I attempted to access the following URL but encountered an access denied message. Is there a specific permission required for this? Here is the exact error I received: The anonymous caller lacks the necessary storage.objects.get access to retrieve the ...

Harnessing the power of external Javascript functions within an Angular 2 template

Within the component, I have a template containing 4 div tags. The goal is to use a JavaScript function named changeValue() to update the content of the first div from 1 to Yes!. Since I am new to TypeScript and Angular 2, I am unsure how to establish comm ...