Skip to content
Advertisement

How to replace array values with another arrays values in Angular8

I have two sample data named oldArray and newArray.

I want to replace oldArray objects with newArray objects if makeLineName and makeProcessTypeId of both oldArray and newArray is same.

For Ex – In oldArray, we have TestDemo1 and Test565 makeLineName available and same TestDemo1 and Test565 makeLineName available in newArray also, So i want to search newArray for this TestDemo1 and Test565 makeLineName and if same makeLineName availalble in newArray than replace the fields values of oldArray makelinename with same makelinename object of newarray.

and if same makelinename is not available in newArray, then oldArray object which not matched than it will remain as it is.

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
      }
    ];

Advertisement

Answer

You can use this line of code :

let resultArray = oldArray.map(el => newArray.find(f => f.makeLineName == el.makeLineName) ?? el);

to solve you error try :

let resultArray = oldArray.map(el =>  {
    let newElement = newArray.find(f => f.makeLineName == el.makeLineName);
    return newElement ? newElement : el;
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement