I need to concatenate two objects that have the same id
.
Example:
a1: {id: 1, qtde: 2}
a2: {id:1, nome: 'teste'}
Result:
a3: {id: 1, nome: 'teste', qtde: 2}
Does anyone know how to do it?
I need to concatenate two objects that have the same id
.
Example:
a1: {id: 1, qtde: 2}
a2: {id:1, nome: 'teste'}
Result:
a3: {id: 1, nome: 'teste', qtde: 2}
Does anyone know how to do it?
If the only key
that the objects have in common is id
and you are sure that the value will always be the same, then just iterate over the properties of the objects and add the values to the third object: / p>
var a1 = {
id: 1,
qtde: 2
};
var a2 = {
id: 1,
nome: 'teste'
};
var a3 = {}
Object.keys(a1).forEach(function(key) {
a3[key] = a1[key];
});
Object.keys(a2).forEach(function(key) {
a3[key] = a2[key];
});
document.write(JSON.stringify(a3));
Given that JavaScript reference objects, you have two paths:
To add, you can do a function to combine (merge ) these objects.
function mergeInto(source, target) {
Object.keys(source).forEach(function(key) {
target[key] = source[key];
});
}
In this case, the function does not need return
because the target
object is changed by reference.
Example: link
To keep the originals , as indicated by the response from @tayllan , you have to create a third object and to add features of both. In this case it might be so, and the function would already have to have return
:
function mergeObjects(sourceA, sourceB) {
var obj = {};
var keys = Object.keys(sourceA).concat(Object.keys(sourceB));
keys.forEach(function(key) {
if (sourceA.hasOwnProperty(key)) obj[key] = sourceA[key];
if (sourceB.hasOwnProperty(key)) obj[key] = sourceB[key];
});
return obj;
}
var c = mergeObjects(a, b); // Object {id: 1, nome: "teste", qtde: 2}
Example: link