1

I am trying to combine two object arrays using either Javascript or Jquery but it is not resulting the way I am expecting it to be. These are my array objects results:

Arry1 Results: [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}]

Arry2 Results: [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}]

This is what I have done to push one into the other:

Array.prototype.push.apply(Arry1,Arry2);

The issue is the above code stacks them together. The object structure I am trying to get is as follows:

[ 
{
 "name": "2412",
 "zip": "12051"
},
{
 "name": "3324",
 "zip": "54021"
},
{
"name": "8875",
 "zip": "24521"
}
]
Zeusox
  • 7,708
  • 10
  • 31
  • 60

3 Answers3

2

Map the arrays into each other by cloning and combining with Object.assign

let a1 = [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}];

let a2 = [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}];

let result = a1.map((props, index) => Object.assign(props, a2[index]));

console.log(result);

Edit Based on Comment:

If this is a utility you're going to be using often with a variable number of arrays, you may consider creating a function that handles it.

    let a1 = [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}],
    a2 = [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}],
    a3 = [{"phone": "1234"},{"phone": "3121"},{"phone": "2136"}];


function combine(first, ...arrs) {
  let result = first.map((props, index) => {
    let combined = [props];
    arrs.forEach(arr => combined.push(arr[index]));
    return Object.assign(...combined);
  })
  return result;
};


let result = combine(a1, a2, a3);
console.log(result);
zfrisch
  • 8,474
  • 1
  • 22
  • 34
1

There are multiple ways to do this. The below is one of,

let array1 = [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}];
let array2 = [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}];
let resultArray = [];
for(let i=0; i< array1.length; i++) { // we can consider any of array1 or array 2 length
  resultArray.push({...array1[i], ...array2[i]});
}
console.log(resultArray);

OR

With Jquery, we can go like below,

let array1 = [{ name: "2412" }, { name: "3324" }, { name: "8875" }];
let array2 = [{ zip: "12051" }, { zip: "54021" }, { zip: "24521" }];

let resultArray = [];
$.each(array1, function(index, value) {
   resultArray.push($.extend(value, array2[index]));
});
console.log(resultArray);
Gangadhar Gandi
  • 2,162
  • 12
  • 19
1

You can use map:

const arr1 = [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}];

const arr2 =  [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}];

let result = arr1.map((obj, idx) => {
      obj.zip = arr2[idx].zip; 
      return obj
  });

console.log(result)
Addis
  • 2,480
  • 2
  • 13
  • 21