Given two object, named: ObjectA and ObjectB:
var ObjectA = {
config1: "5",
config2: "6",
config3: "7"
}
var ObjectB = {
config1: "1",
config2: "2",
config4: "3",
config5: "4"
}
How can I copy from ObjectB to ObjectA so that ObjectA have the same properties of ObjectB while the values of properties in ObjectA is kept and values from ObjectB that doesn't exist in ObjectA is copied to ObjectA?
Expected result:
ObjectA = {
config1: "5",
config2: "6",
config4: "3",
config5: "4"
}
config3is deleted since it doesn't exist inObjectB,config4withconfig5are copied toObjectAsince those doesn't exist inObjectA,- and value in
config1withconfig2are kept the same inObjectAsince those two exist in both of the object)
CodePudding user response:
Use reduce:
ObjectA = Object.keys(ObjectB).reduce(
(acc, key) => ({ ...acc, [key]: ObjectA[key] ?? ObjectB[key]}), {}
)
This will use the keys from ObjectB, take values from ObjectA, when they exist (with fallback to ObjectB), and populate an empty object with the results.
CodePudding user response:
You can use the reducer function to solve.
var ObjectA = {
config1: "5",
config2: "6",
config3: "7"
}
var ObjectB = {
config1: "1",
config2: "2",
config4: "3",
config5: "4"
}
const res = Object.keys(ObjectB).reduce((prev, next) => {
if(ObjectA[next]){
prev[next] = ObjectA[next];
}
return prev;
}, {...ObjectB})
console.log(res)
