简体   繁体   中英

add key and values of array A to array B in javascript

I have these two arrays of objects:

A = [
{a: 'john', b: 'joe', c: 'jack'},
{a: 'ben', b: 'alex', c: 'nicole'},
{a: 'sarah', b: 'megan', c: 'bill'}
]
B = [
{x: 'texas', y: 'cali', z: 'washington'},
{x: 'omaha', y: 'hawaii', z: 'york'},
{x: 'michigan', y: 'dakota', z: 'alabama'}
]

I want to merge their object values together so I have something like this:

C = [
{a: 'john', b: 'joe', c: 'jack', x: 'texas', y: 'cali', z: 'washington'},
{a: 'ben', b: 'alex', c: 'nicole', x: 'omaha', y: 'hawaii', z: 'york'},
{a: 'sarah', b: 'megan', c: 'bill', x: 'michigan', y: 'dakota', z: 'alabama'}
]

How can I do that?

try this

var C = A.map((x, i) => Object.assign(x, B[i]) )
var mergeArray = (A, B) => { const res = [] for(let i = 0; i < A.length; i++ ) { res.push({...A[i], ...B[i]}) } return res }

Use map and spread (...) operator

 A = [ { a: "john", b: "joe", c: "jack" }, { a: "ben", b: "alex", c: "nicole" }, { a: "sarah", b: "megan", c: "bill" }, ]; B = [ { x: "texas", y: "cali", z: "washington" }, { x: "omaha", y: "hawaii", z: "york" }, { x: "michigan", y: "dakota", z: "alabama" }, ]; C = A.map((obj, i) => ({...obj, ...B[i] })); console.log(C);

Try this:

 let C = []; for(let i = 0; i < A.length; i++){ C.push(A[i]); Object.assign(C[i], B[i]); } console.log(C)

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