Issue
example:
Below there are 2 json objects with different values and I want to make it as one final Json object and append new value to the final result
let json1= {
"b":"test1",
"a":"test3",
"type":"sample1"
}
let json2= {
"b":{
"endDate":"ddd1",
"startDate":"dd01"
},
"a":{
"endDate":"31",
"startDate":"01"
},
"type":"sample2"
}
Expected results should be like below
let result = {
"b":{
"endDate":"ddd1",
"startDate":"dd01",
"XYZ":"test1"
},
"a":{
"endDate":"31",
"startDate":"01",
"XYZ":"test3"
},
}
Can anyone help please using JavaScript or loadash functionality
Solution
You can use the rest operator to remove type property and then assign values from 1st object to new property of the merged object
let mergeObjects = (a, b) => {
let {type, ...rest} = b; //remove type property
for(let prop in rest){
if(a[prop]){
rest[prop].xyz = a[prop];
}
}
return rest;
}
let Object3= mergeObjects(Object1, Object2);
console.log(Object3);