简体   繁体   中英

Merge two array of objects together

I have two array of object and i would like to merge them together so i can map them and display the data in the frontend.

const arr1 = [{id: 1, symbol: "France", position: "South"},{id: 2, symbol: "Sweden", city: "Malmo"}]

const arr2 = [{id: 1, symbol: "USA", city: "Los angeles"},{id: 2, symbol: "France", city: "Paris"}]

Expected output:

const arr3 =[{id: 1, symbol: "France", city: "Paris", position: "South"}, {id: 1, symbol: "USA", city: "Los angeles"} ]

Here is my solution but i'm not getting the output that i want.

 const arr1 = [{id: 1, symbol: "France", position: "South"},{id: 2, symbol: "Sweden", city: "Malmo"}] const arr2 = [{id: 1, symbol: "USA", city: "Los angeles"},{id: 2, symbol: "France", city: "Paris"}] const countries = arr1.map((item, i) => { return Object.assign({}, item, arr2[i]); }); console.log(countries)

you can use concat like this to merge two array

 const arr1 = [{id: 1, symbol: "France", position: "South"},{id: 2, symbol: "Sweden", city: "Malmo"}] const arr2 = [{id: 1, symbol: "USA", city: "Los angeles"},{id: 2, symbol: "France", city: "Paris"}] const countries = arr1.concat(arr2) console.log(countries)

Your expected output is not possible as per your question. my answer may be helpful for you if you are looking something like this

 const arr1 = [{id: 1, symbol: "France", position: "South"},{id: 2, symbol: "Sweden", city: "Malmo"}]; const arr2 = [{id: 1, symbol: "USA", city: "Los angeles"},{id: 2, symbol: "France", city: "Paris"}]; const arr3 = [...arr1,...arr2]; console.log(arr3);

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