1

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
 });
 }
 }
Mohammad Usman
39.6k20 gold badges99 silver badges101 bronze badges
asked Dec 5, 2018 at 12:46

1 Answer 1

5

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

answered Dec 5, 2018 at 12:49
Sign up to request clarification or add additional context in comments.

1 Comment

Also thank you for the CSS wrapper, didn't know you could do that !

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.