'JavaScript Concatenate Nested Objects Spread Operator
I have the following example code.
var myObj1 = {
name: {
first: "First",
last: "Last"
}
};
var myObj2 = {
name: {
first: "Other",
middle: "Middle"
}
};
var myMainObj = {
...myObj1,
...myObj2
};
console.log(myMainObj);
I expect myMainObj
to be the following:
{
name: {
first: "Other",
middle: "Middle",
last: "Last"
}
}
But myMainObj
ends up being:
{
name: {
first: "Other",
middle: "Middle"
}
}
So I have two objects. I want to basically combine them, and have the ability to assign priority to one of the objects over another.
Both objects come from external sources, so the structure and data is not guaranteed, and I have to account for the data being in different structure.
How can I do this easily since the spread operator only works for the root level of the object?
I am looking for the cleanest and easiest solution to do this.
Solution 1:[1]
You can use .merge
method from lodash lib for this. The work already done by lodash maintainers, no need to reinvent the wheel, just use their lib.
This method is like
_.assign
except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object.
var myObj1 = {
name: {
first: "First",
last: "Last"
}
};
var myObj2 = {
name: {
first: "Other",
middle: "Middle"
}
};
var myMainObj = _.merge({}, myObj1, myObj2)
console.log(myMainObj);
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
Solution 2:[2]
This should do:
var myMainObj = {
name: {
...myObj1.name,
...myObj2.name
}
};
You will have to implement your own merger if you need to perform a deeper merge.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Derek 朕會功夫 |