Merge two arrays of objects in javascript

2

I wanted to know how I can merge two% co_of% of objects * (inserting one into another would also help me). *

For example:

array["nombre": "paco", "edad": "21"];
array2["nombre": "matias", "edad": "25"];

would look like this:

arraydefinitivo[array, array2]

I've tried with arrays , but it does not work for me.

    
asked by victor96 22.02.2018 в 02:04
source

2 answers

4

You can use concant to join 2 arrays

var array1=[1,2,3];
var array2=[4,5,6];
array1=array1.concat(array2);
console.log(array1);

Other alternative [].concat(array1, array2, array3);

var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = [7, 8, 9];
array1 = [].concat(array1, array2, array3);
console.log(array1);

Now if you want to concatenate discriminating by some condition, for example just concatenate the even numbers of 2 arrays

var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

array2.filter(data => data%2==0 ? array1.push(data):data);
console.log(array1);
    
answered by 22.02.2018 / 02:11
source
1

The problem is in the declaration of an array of objects. The correct thing would be:

var array1 = [
  {"nombre": "paco", "edad": "21"}
 ];

var array2 = [
  {"nombre": "matias", "edad": "25"}
 ];

Then you use concat to join both:

array1 = array1.concat(array2);

The complete example would be:

var array1 = [
  {"nombre": "paco", "edad": "21"}
];

// Array con 2 objetos
var array2 = [
  {"nombre": "matias", "edad": "25"},
  {"nombre": "juan", "edad": "31"},
];

array1 = array1.concat(array2);
console.log(array1);
    
answered by 23.02.2018 в 23:54