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
Can be as simple as this:
let Object1 ={"b":"test1","a":"test3","type":"sample1"};let Object2 ={"b":{"endDate":"ddd1","startDate":"dd01"},"a":{"endDate":"31","startDate":"01"},"type":"sample2"} let Object3 = Object2; for (let i in Object3){ Object3[i]["XYZ"] = Object1[i] } Object3["type"] = "12345" console.log(Object3)
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.