Languages
[Edit]
EN

JavaScript - merge two arrays of objects

0 points
Created by:
Blessing-D
574

In this article, we would like to show you how to merge two arrays of objects in JavaScript.

1. Using concat() method

// ONLINE-RUNNER:browser;

var array1 = [
    { id: 1, value: 'a' },
    { id: 2, value: 'b' }
];

var array2 = [
    { id: 3, value: 'c' },
    { id: 4, value: 'd' }
];

var array3 = array1.concat(array2);

console.log(JSON.stringify(array3, null, 4));

2. Using apply() method with push()

// ONLINE-RUNNER:browser;

var array1 = [
    { id: 1, value: 'a' },
    { id: 2, value: 'b' }
];

var array2 = [
    { id: 3, value: 'c' },
    { id: 4, value: 'd' }
];

Array.prototype.push.apply(array1, array2);

console.log(JSON.stringify(array1, null, 4));

3. Using spread syntax (...)

Example 1

// ONLINE-RUNNER:browser;

var array1 = [
    { id: 1, value: 'a' },
    { id: 2, value: 'b' }
];

var array2 = [
    { id: 3, value: 'c' },
    { id: 4, value: 'd' }
];

var array3 = [...array1, ...array2];

console.log(JSON.stringify(array3, null, 4));

Example 2

// ONLINE-RUNNER:browser;

var array1 = [
    { id: 1, value: 'a' },
    { id: 2, value: 'b' }
];

var array2 = [
    { id: 3, value: 'c' },
    { id: 4, value: 'd' }
];

array1.push(...array2);

console.log(JSON.stringify(array1, null, 4));

 

See also

  1. JavaScript - merge two arrays

References

  1. Array.prototype.concat() - JavaScript | MDN 
  2. Spread syntax (...) - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join