Learn the process of swapping out array values with values from another array in Angular8

I have two sets of data called oldArray and newArray.

The goal is to update objects in oldArray with those from newArray if the makeLineName and makeProcessTypeId are the same in both arrays.

For example - In oldArray, we have TestDemo1 and Test565 under makeLineName, and these same values are also present in newArray. Therefore, I need to search for TestDemo1 and Test565 in newArray and replace the respective fields in oldArray with the matching makeLineName object from newArray.

If a matching makeLineName is not found in newArray, then the original object in oldArray will remain unchanged.

oldArray = [
      {       
        makeLineName: "TestDemo1",
        avtBCT: 80,
        MaxBCT: 80
      },
      {      
        makeLineName: "Test565",
        avtBCT: '',
        MaxBCT: ''
      },
      {      
        makeLineName: "Luck", 
        avtBCT: 60,
        MaxBCT: 60
      }
    ];

    const newArray = [
      {       
        makeLineName: "TestDemo1",
        avtBCT: 500,
        MaxBCT: 500
      },
      {      
        makeLineName: "Test565",
        avtBCT: 600,
        MaxBCT: 600
      }
    ];

Expected Output:

filteredData = [
      {       
        makeLineName: "TestDemo1",
        avtBCT: 500,
        MaxBCT: 500
      },
      {      
        makeLineName: "Test565",
        avtBCT: 600,
        MaxBCT: 600
      },
      {      
        makeLineName: "Luck", 
        avtBCT: 60,
        MaxBCT: 60
      }
    ];

Answer №1

If you're facing an issue, you can address it by utilizing the following code snippet :

let updatedArray = initialArray.map(element => newArray.find(item => item.name === element.name) ?? element);

To rectify any errors, consider implementing this alternative approach :

let updatedArray = initialArray.map(element => {
    let newElement = newArray.find(item => item.name === element.name);
    return newElement ? newElement : element;
});

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

In the strict mode tree, a reference named "grid" has been discovered

I encountered the following warning in the console: Warning: A string ref, "grid", has been found within a strict mode tree. String refs can potentially lead to bugs and should be avoided. It is recommended to use useRef() or createRef() instead. T ...

Listen to music on an Android device without disturbing anyone using an iPhone

I have an application built in Vue3 that plays a sound when a QR code is scanned. This feature works perfectly on Android and the web, but not when using the browser on iOS. I am struggling to identify the issue. Can anyone provide some insight? <qrco ...

Is it possible to bind HTML within an AngularJS partial but encountering an inexplicable issue?

I'm facing an issue with my ng-repeat that involves using a partial HTML file to loop through and display items on a page. The variables within the partial are not displaying, but interestingly enough, the variable {{rule.name}} outside of the partial ...

How can I set a condition to open a specific page in ReactJs?

Currently, I am in the process of developing a website and have successfully implemented a profile page. This profile page consists of three buttons - Settings, Favourites, and Posts. To enhance user experience, I decided to structure it as a multi-step fo ...

Sending an object between two components without a direct parent-child connection

Hello, I have a question similar to the one asked on Stack Overflow regarding passing a value from one Angular 2 component to another without a parent-child relationship. In my scenario, Component1 subscribes to a service that makes a GET request to the ...

Snackbar expands to cover the entire screen upon deployment

The issue with the oversized snackbar only seems to occur in the deployed version, and I'm unable to identify the root cause. I am hoping someone can provide insight on what adjustments can be made in the StackBlitz project to prevent this bug from ap ...

Is there a way to display nested object values within an object using VueJs?

I am encountering an issue where my code is not printing out values from an object correctly. The nested objects are displaying the entire object as { propName: value } on the UI. Below is the HTML code: <ul class="o-pf-list"> <li v-for="(v ...

Ways to retrieve the value of a field using ng-change

I have been working with ng-change in AngularJS to react to user input in a textarea. However, I am struggling to figure out how to access the current input inside the Angular controller without using something like $(this).value(); in jQuery. <scrip ...

I have noticed that there are 3 images following the same logical sequence, however only the first 2 images seem to be functioning correctly. Can you help

Update: I have found a solution that works. You can check it out here: https://codepen.io/kristianBan/pen/RwNdRMO I have a scenario with 3 images where clicking on one should give it a red outline while removing any outline from the other two. The first t ...

Can you explain the meaning of the symbol >>=?

I'm confused about the meaning of >>= (I thought it was greater than or equal to as >=). Can you also explain what (times & 1) means in the code snippet below? function repeat (string, times) { var result = '' while (times > 0) ...

Using jQuery to add content after an AJAX request

Here's my scenario: I have an element that, using AJAX, loads search results into it. html <input class="search"> <div class="search-results"> // starts off empty // after search, add <a></a> </div> jquery $("input ...

When it comes to TypeScript, one can always rely on either event.target or event

I'm a beginner with TypeScript and currently in the process of refactoring an arrow function within React.js. Here is the current implementation: handleChange = (event): void => { const target = event.target || event.srcElement; this.s ...

I am looking to modify various attributes linked to Rails

My Desire for Reality I am looking to update multiple related values in Rails by sending an update request from JavaScript. While creating data was seamless, I encountered difficulties when attempting to update it. #Code JavaScript* export const actions ...

Dynamically obtaining the screen width in JSP using a variable

Could someone provide assistance on how to resize an image using an img src="blah.jpg?width=x" so that my page can be displayed at various sizes? I just need x (width) as a JSP variable. Update 2021: It's been 9 years since this question wa ...

There is no XHR request sent when invoking the http function

I am facing challenges in configuring a service in angular2 to interact with a REST backend. My attempt at setting up a basic example for sending requests to a rest backend and handling the response seems to be on track. The Service is being called correc ...

What is the correct way to position a material-ui icon within a button for proper alignment?

Is there a way to properly align the <ChevronRightIcon> within the <PrimaryButton>? I want it to appear after the button label on the right side. https://i.stack.imgur.com/dcEWo.png <PrimaryButton style={{ paddingRight: &apo ...

What CSS property prevents a fixed header from overlapping a scrolled element?

After creating a fixed header for my HTML table, I noticed that as I scroll down the page, everything is being overlapped by the fixed header except for one slider (noUiSlider). I am curious to know which CSS property is preventing the header from overlayi ...

I am looking to incorporate a password recovery page into my login process, but I am facing difficulty navigating to it once the code has been modified

I'm looking to include a forgotten password option on my login page, but I'm facing an issue when trying to navigate to it after updating the code. The website is throwing the following error message: [vue-router] uncaught error during rout ...

Could anyone provide an explanation of the current situation in this section of the code?

I am currently working on a piece of code that looks like this: ruter.get('/', async function (_, res) { const [categories, items] = (await Promise.all([ db.query('SELECT * FROM categories'), db.query('SELECT * FROM invento ...

The reactivity system in Vue does not support string arrays when paired with TypeScript

My UI is designed for users to create 1:n mappings for form fields. The structure of the model is quite straightforward: export interface IMapping { pdfName: string; fieldNames: string[]; } However, I encountered a problem with reactivity when it ...