2

I have two array of objects like below:

array_1 = [
            {'id': 1},
            {'id': 2},
            {'id': 3},
            {'id': 4},
            {'id': 5}
          ];
array_2 = [
            {'name': 'Doe', 'age': 45},
            {'name': 'John', 'age': 35}
          ];

I want to concatenate these two arrays to make one array like this:

result_array = [
                 {'id': 1, 'name': 'Doe', 'age': 45},
                 {'id': 2, 'name': 'John', 'age': 35},
                 {'id': 3},
                 {'id': 4},
                 {'id': 5}
               ]

I tried:

var result_array = array_1.concat(array_2);

But it gives:

result_array = [
                 {'name': 'Doe', 'age': 45},
                 {'name': 'John', 'age': 35},
                 {'id': 1},
                 {'id': 2},
                 {'id': 3},
                 {'id': 4},
                 {'id': 5}
              ]

How can I do this?

Mamun
  • 66,969
  • 9
  • 47
  • 59
Kiki
  • 333
  • 2
  • 12

7 Answers7

2

Your required output suggests that you need to merge objects in the matching position (not concatenation) from the arrays.

You can use Array.prototype.map():

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

and Object.assign():

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Try the following way:

var array_1 = [
            {'id': 1},
            {'id': 2},
            {'id': 3},
            {'id': 4},
            {'id': 5}
          ];
var array_2 = [
            {'name': 'Doe', 'age': 45},
            {'name': 'John', 'age': 35}
          ];

var result_array = array_1.map((obj, idx) => {
  if(idx < array_2.length){
    obj = Object.assign(obj, array_2[idx]);
  }
  return obj;
});

console.log(result_array);
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

Just one more way:

let array_1 = [
            {'id': 1},
            {'id': 2},
            {'id': 3},
            {'id': 4},
            {'id': 5}
          ]
let array_2 = [
            {'name': 'Doe', 'age': 45},
            {'name': 'John', 'age': 35}
          ]

let tmp = array_1.length > array_2.length ? array_1 : array_2

let result = tmp.reduce((acc, val, i) => {
  acc.push({...(array_1[i] || []), ...(array_2[i] || [])})
  return acc
}, [])

console.log(result)

I check for longest array in order to merge those if array_1 is smaller than array_2.

Georgy
  • 2,410
  • 3
  • 21
  • 35
0

Loop over array_1 and for each object in array_1, create a new object with the contents of array_1[i] and array_2[i] where i is your for loop iterator. Push this new object into a new array.

You can use Object.assign() to concatenate the 2 objects.

0
array1 = [
            {'id': 1},
            {'id': 2},
            {'id': 3},
            {'id': 4},
            {'id': 5}
          ];

array2 = [
            {'name': 'Doe', 'age': 45},
            {'name': 'John', 'age': 35}
          ];

          var newArray = [];
for (var i = 0; i < array1.length; i++) {
    var obj = array1[i];
    if (array2[i]) {
        for (key in array2[i]) {
            obj[key] = array2[i][key];
        }
        newArray.push(obj);
    }
};


          console.log(Object.assign(array1, newArray))
mepraveenk
  • 226
  • 1
  • 11
0

Concat is not what you're looking for in this case, you want to use map.

Something like this,

array_3 = array_1.map(function(a, i){
    if(i < array_2.length){
        return Object.assign({},a, array_2[i]);
    }
    else {
        return a;
    }
});

Note: You might need additional checks to ensure condition where array_2 is longer/larger than array_1.

noobius
  • 1,529
  • 7
  • 14
0

Use array reduce and during each iteration check if in the array_2 have and element in that index corresponding to array_1

let array_1 = [{
    'id': 1
  },
  {
    'id': 2
  },
  {
    'id': 3
  },
  {
    'id': 4
  },
  {
    'id': 5
  }
]
let array_2 = [{
    'name': 'Doe',
    'age': 45
  },
  {
    'name': 'John',
    'age': 35
  }
]

let finalArray = array_1.reduce(function(acc, curr, index) {
  acc.push({
    id: curr.id
  });

  if (array_2[index] !== undefined) {
    acc[index].name = array_2[index].name;
    acc[index].age = array_2[index].age
  }

  return acc;
}, []);

console.log(finalArray)
brk
  • 48,835
  • 10
  • 56
  • 78
0

You can use it as below, Object.assign - To add the two different matched object and splice - to Unset the element and append the objects at the beginning of the array.

array_1 = [
            {'id': 1},
            {'id': 2},
            {'id': 3},
            {'id': 4},
            {'id': 5}
          ]
array_2 = [
            {'name': 'Doe', 'age': 45},
            {'name': 'John', 'age': 35}
          ]

var obj;
for (let key of array_1.keys()) 
{
 for (let key1 of array_2.keys()) 
 {
  if(key == key1)
  {
   obj = Object.assign({}, array_1[key], array_2[key]); // Assigns matched keys 
   array_1.splice(key, 1); // Remove the matched keys from array_1
   array_1.unshift(obj); // appends the object to array_1
  }
 }
}
console.log(array_1.sort()); 
lifeisbeautiful
  • 817
  • 1
  • 8
  • 18