-2

I am trying to combine two arrays in the following way.

var x = [{'d1':'3'}, {{'d2':'4'}}, {{'d3':'5'}}]
var y = [{'c1':'3'}, {{'c2':'4'}}, {{'c3':'5'}}]

my result should look like this

z = [
{'d1':'3', 'c1':'3' },
{'d1':'4', 'c1':'4' },
{'d1':'5', 'c1':'5' },
]
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
user821
  • 53
  • 7
  • Does this answer your question? [How do I zip two arrays in JavaScript?](https://stackoverflow.com/questions/22015684/how-do-i-zip-two-arrays-in-javascript) – user120242 May 28 '20 at 05:41
  • 1
    @user120242 it isn't a zip operation, as you end up with a flat array, not an array of tuples. – VLAZ May 28 '20 at 06:25

2 Answers2

1

Cleaning up you syntax abit this is what I end up with:

let x = [{d1:'3'}, {d2:'4'}, {d3:'5'}];
let y = [{c1:'3'}, {c2:'4'}, {c3:'5'}];

// create a new list to store the objects we'll create
let z = [];

[x, y].forEach(array => {
  // loop through the values for this line
  for (i=0; i < array.length; i++) {
    // handle case where we need to add more objects to our list
    if (z.length <= i) z.push({});
    // add new kay and value
    z[i][Object.keys(array[i])[0]] = array[i][Object.keys(array[i])[0]];
  }
});

console.log(z)

Note that by changing [x,y] to more lists such as [x,y,z,w] this code will still work assuming they are all the same size :)

View live example here.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
James
  • 56
  • 8
0

Your bracket notation for the objects is wrong. You have two sets of brackets instead of one.
Simple map that merges the objects using index position and spread operator.

var x = [{'d1':'3'}, {'d2':'4'}, {'d3':'5'}]
var y = [{'c1':'3'}, {'c2':'4'}, {'c3':'5'}]

console.log(
z=x.map((x,i)=>([{...x,...y[i]}]))
)

    var x = [{'d1':'3'}, {'d2':'4'}, {'d3':'5'}]
    var y = [{'c1':'3'}, {'c2':'4'}, {'c3':'5'}, {'g6':'6'}]

    // needed for different length arrays, pads array with objects and y falsey check
    console.log(
    z=(x.length<y.length?x.concat(Array(y.length-x.length).fill({})):x)
         .map((x,i)=>([{...x,...y[i]||{}}]))
    )
user120242
  • 14,918
  • 3
  • 38
  • 52