SkyWalker
SkyWalker

Reputation: 14309

How to recursively merge two objects?

I have the following two objects:

var objectA = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0
        },
    ]
};

var objectB = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "sharpe": 2.5
        },
    ]
};

and I'd like to get:

var objectC = {
    "a": [
        {
            "col": 1,
            "row": 1,
            "pnl": 1.0,
            "sharpe": 1.5
        },
        {
            "col": 1,
            "row": 2,
            "pnl": 2.0,
            "sharpe": 2.5
        },
    ]
};

Upvotes: 1

Views: 275

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386570

You could use a hash table for reference to the same key and col/row items. Then update the object or assign the new object if no hash is available.

var objectA = { a: [{ col: 1, row: 1, pnl: 1.0 }, { col: 1, row: 2, pnl: 2.0 }] },
    objectB = { a: [{ col: 1, row: 1, sharpe: 1.5 }, { col: 1, row: 2, sharpe: 2.5 }] },
    hash = Object.create(null);

Object.keys(objectA).forEach(function (k) {
    hash[k] = hash[k] || {};
    objectA[k].forEach(function (o) {
        var key = ['col', 'row'].map(function (l) { return o[l]; }).join('|');
        hash[k][key] = o;
    });
});

Object.keys(objectB).forEach(function (k) {
    if (!hash[k]) {
        objectA[k] = objectB[k];
        return;
    }
    objectB[k].forEach(function (o) {
        var key = ['col', 'row'].map(function (l) { return o[l]; }).join('|');
        if (hash[k][key]) {
            Object.keys(o).forEach(function (l) {
                hash[k][key][l] = o[l];
            });
        } else {
            objectA[k].push(o);
        }
    });
});

console.log(objectA);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Misha Reyzlin
Misha Reyzlin

Reputation: 13896

I would use lodash’s _.merge method in this case.

This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

https://lodash.com/docs/4.17.4#merge

Or if you need it to not be part of a library, then look at the lodash’s implementation.

Upvotes: 1

Faly
Faly

Reputation: 13346

Just use Object.assign to merge objects:

var json1 = {"a":[ 
               {
                 "col": 1, 
                 "row": 1,
                 "pnl": 1.0
               },
               {
                 "col": 1, 
                 "row": 2,
                 "pnl": 2.0
               },  
           ]};

var json2 = {"a":[ 
               {
                 "col": 1, 
                 "row": 1,
                 "sharpe": 1.5
               },
               {
                 "col": 1, 
                 "row": 2,
                 "sharpe": 2.5
               },  
           ]};
           
 var objectC = { a: json1.a.map((el, index) => Object.assign({}, el, json2.a[index])) };
 console.log(objectC);

Upvotes: 0

Related Questions