1

In javascript, let say there are 2 objects, objectA and objectB.

I want to change objectA's value to objectB's value, if objectB has objectA's key and value.

How can I approach this problem?

let objectA = {
    "key1" : {
        "key1_1" : "a",
        "key1_2" : "b"
    },
    "key2" : {
        "key2_1" : 1,
        "key2_2" : 2,
        "key2_3" : 3
    },
};
let objectB = {
    "key1" : {
        "key1_1" : "assign_a"
    },
    "key2" : {
        "key2_2" : 5,
        "key2_3" : 6
    },
};

let i_want_this_result_assignedObjectA = {
    "key1" : {
        "key1_1" : "assign_a",
        "key1_2" : "b"
    },
    "key2" : {
        "key2_1" : 1,
        "key2_2" : 5,
        "key2_3" : 6
    },
};
  • 1
    Please share some approach you tried. – Himanshu Shekhar Apr 17 '20 at 03:39
  • I failed but my approach is using recursive function. 1. list all keys by Object.keys 2. check each key's value is object or not 3. if object -> call recursive function 4. if not object -> assign like this but I couldn't approach to object in object in object ... value by key list. – Hanvit Choi Apr 17 '20 at 03:47
  • Immutablejs has some mergeDeep function that might do what you're looking for. https://immutable-js.github.io/immutable-js/docs/#/mergeDeep – Matt Apr 17 '20 at 03:47
  • Check this one : https://stackoverflow.com/a/8625261/7026966 – Himanshu Shekhar Apr 17 '20 at 03:51

1 Answers1

0

Thanks for comments,

In my case, Markus's answer at stackoverflow.com/a/8625261/7026966 is the answer what I'm looking for.