简体   繁体   中英

Angular 2 how to put object array in to another object array

So I have 2 Arrays (Always equal index ) :

A: [
{name: Jhon1}
{name: Jhon2}
{name: Jhon3}
]

B: [
{lastName: Pom1}
{lastName: Pom2}
{lastName: Pom3}
]

Expected Result after merge :

A: [
   {name: Jhon1, lastName: Pom1}
   {name: Jhon2, lastName: Pom2}
   {name: Jhon3, lastName: Pom3}
]

Concat method just merges the whole array in to one like this :

  A: [
    {name: Jhon1}
    {name: Jhon2}
    {name: Jhon3}
    {lastName: Pom1}
    {lastName: Pom2}
    {lastName: Pom3}
    ]

My own function that I am trying. Below there is two arrays: this.prices and this.search.favoriteItems , I want to merge then the same way as I described before :

showProducts(){
   for(let i of this.localStorageArray){
    let id = localStorage.getItem(i);
    this.search.getProductsById(id).subscribe
    ((data: any) => {
     this.prices.push(data.lowestPrices.Amazon);
     this.search.favoriteItems.push(data);  
   //something here to merge this.prices and this.search
    });

  }
  }

You can use .map() with Object destrcuturing:

 let arr1 = [{name: 'Jhon1'}, {name: 'Jhon2'}, {name: 'Jhon3'}], arr2 = [{lastName: 'Pom1'}, {lastName: 'Pom2'}, {lastName: 'Pom3'}]; let zip = (a1, a2) => a1.map((o, i) => ({...o, ...a2[i]})); console.log(zip(arr1, arr2)); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM