PokerJoker
PokerJoker

Reputation: 211

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

  }
  }

Upvotes: 1

Views: 49

Answers (1)

Mohammad Usman
Mohammad Usman

Reputation: 39322

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

Upvotes: 5

Related Questions