With the following
var a = {
a: 0,
b: [],
c: "",
d: { "x": "y", "g": "f" },
e: {},
f: function () { return undefined; }(),
g: false
};
var b = {
a: { "a": "b" },
b: { "c": "d" },
c: { "e": "f" },
d: { "g": "h" },
e: { "i": "j" },
f: {},
g: { "m": "n" },
};
If you look at the datatypes, I have the falsy or empty version of several (or a close approximation): Number, Array,String,Object,undefined, Boolean.
Using the above with the following:
var assinged = _.assign({}, a, b);
var merged = _.merge({}, a, b);
var extended = _.extend({}, a, b);
I get:
assigned:
{
"a": {"a": "b"},
"b": {"c": "d"},
"c": {"e": "f"},
"d": {"g": "h"},
"e": {"i": "j"},
"g": {"m": "n"}
}
merged:
{
"a":{"a":"b"},
"b":[],
"c":{"e":"f"},
"d":{"x":"y","g":"h"},
"e":{"i":"j"},
"g":{"m":"n"}
}
extended:
{
"a": {"a": "b"},
"b": {"c": "d"},
"c": {"e": "f"},
"d": {"g": "h"},
"e": {"i": "j"},
"g": {"m": "n"}
}
SO, assign and extend are equivalent for this example. Merge does the closest to what I want - You look at the key d
, you can see that my existing key is preserved, and the object is extended. However, looking at the b
key, you can see that the empty array is overwriting the object with Merge.
Two questions:
Is there a simple command in lodash that will achieve what I want (a true, complete deep merge, where all properties in the first object are overwritten or extended with values from the second object)?
What choice is
_.merge
making here, that is causing this to happen?