menu

JavaScript

A community to get help with JavaScript, find jobs, outsource and much more!

Channels
# All channels
view-forward
# General
view-forward
# Jobs
view-forward
# Node.js
view-forward
# React
view-forward
# Snippets
view-forward
# Vanilla
view-forward
# Vue.js
view-forward
Team

Clubbing both complex objects does not work: Javascript

February 14, 2020 at 9:40am

Clubbing both complex objects does not work: Javascript

February 14, 2020 at 9:40am (Edited 4 months ago)
I have an source object that has the following structure
var obj1 = {
type: "type1",
nested: {
level1: [
{ field: "field1", value: "val1"},
{ field: "field2", value: "val2"},
{
level2: [
{
field: "abc",
value: "11",
},
{
field: "abc",
value: "12",
}
]
}
]
},
in: 0,
out: 20
};
`
Also there is an input object, based on which merging should happen
var obj2 = { type: "type1", nested: { level1: [ { field: "field1", value: "val1"}, { field: "field3", value: "val5" } ] }, in: 0, out: 20 };
```
Based on the new object I need to merge and resultant should hold only the unique one's. In my case the object can go deep upto level 2. The only thing I need is a manipulation on "nested" object. If same keys are present then update the value, else just append it. Also content within "nested" of obj2 will always be there in obj1's "nested". If something of obj2's "nested" is not present in obj1's "nested" then delete that object. Test cases file attached inside sandbox
Output should look like:
```
result = {
type: "type1",
nested: {
level1: [
{ field: "field1", value: "val1"},
{ field: "field2", value: "val2"},
{ field: "field3", value: "val5" },
{
level2:
[
{
field: "abc",
value: "11",
},
{
field: "abc",
value: "12",
}
]
}
]
},
in: 0,
out: 20
};
```
Method that I have tried:
const merged = [...new Set([...obj1.nested.level1, ...obj2.nested.level1])]
````````
Sandbox:
No messages yet