Problem when merging two objects in JavaScript

2

I have to merge two objects into one, I put simple examples of what I need to do:

var obj1 = [
        { Prop1 : 'Valor 1A',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1B',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1C',  Prop2 : 'Valor 2A' }
];

var obj2 = { Prop3 : 'Valor 3A', Prop4 : 'Valor 4A', Prop5 : 'Valor 5A' }

And I have to create a final object that has this result:

var obj1 = [
        { Prop1 : 'Valor 1A',  Prop2 : 'Valor 2A', Prop3 : 'Valor 3A' },
        { Prop1 : 'Valor 1B',  Prop2 : 'Valor 2A', Prop4 : 'Valor 4A' },
        { Prop1 : 'Valor 1C',  Prop2 : 'Valor 2A', Prop5 : 'Valor 5A' }
];

What I need is to make a merge of objects in which each key / value of obj2 is added in each item of obj1. I tried to do this but it does not return the correct result.

obj1.forEach(function(elem) {  
    for(i in obj2) {
        elem['prop_nueva'] = obj2[i];
    }
});  

I hope your help, thank you.

    
asked by user95442 02.08.2018 в 12:09
source

2 answers

0

Look to see what you think:

var obj1 = [
        { Prop1 : 'Valor 1A',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1B',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1C',  Prop2 : 'Valor 2A' }
];

var obj2 = { Prop3 : 'Valor 3A', Prop4 : 'Valor 4A', Prop5 : 'Valor 5A' }

Object.prototype.merge = function(obj2){
   let i=0, keys = Object.keys(obj2);
  for( o of this){  
    this[i][keys[i]] = obj2[keys[i]];
    i++;
  }
}

obj1.merge(obj2)

console.log(obj1)

is putting you key: value of the second object at the end of each object in the first list.

    
answered by 02.08.2018 / 12:31
source
1

You can do it like this:

var obj1 = [
        { Prop1 : 'Valor 1A',  Prop2 : 'Valor 2A' },
        { Prop1 : 'Valor 1B',  Prop2 : 'Valor 2B' },
        { Prop1 : 'Valor 1C',  Prop2 : 'Valor 2C' }
];

var obj2 = { Prop3 : 'Valor 3A', Prop4 : 'Valor 4A', Prop5 : 'Valor 5A' }

let i=0;
for (propiedad in obj2) {
  console.log('copia', propiedad,'a', obj1[i]);
  obj1[i][propiedad]=obj2[propiedad];
  i++;
}
console.log(obj1);

You have to make sure that the number of properties and the number of elements in the array are compatible

    
answered by 02.08.2018 в 12:23