Merge two objects with the same ID

Asked

Viewed 495 times

1

I need to concatenate two objects that have the same id.

Example:

a1: {id: 1, qtde: 2}
a2: {id:1, nome: 'teste'}

Upshot:

a3: {id: 1, nome: 'teste', qtde: 2}

Someone knows how to do?

  • If you want you can mark one of the answers as accepted.

2 answers

3

Taking into account that Javascript reference objects, you have two paths:

  • add properties to the original object
  • create an object with the properties of others (without changing the originals)

To add, you can do a function to match (do 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 to return for the object target is changed by reference.

Example: https://jsfiddle.net/5pu4n3h9/

To keep the originals, how does the @tayllan, you have to create a third object and add properties of both. In that case it could 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: https://jsfiddle.net/5pu4n3h9/2/

  • 1

    really, encapsulating in a function makes it clearer. And using the .hasOwnProperty() to ensure that you will not take inherited property by the prototype chain is also a good one. + 1.

2

If the only key that objects have in common is id and you are sure that the value will always be the same, so just iterate over the properties of the objects and add the values to the third object:

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));

  • 1

    That would make a job even better :) +1

  • Thanks guys, it worked out.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.