I'm looking for a way to replace object key values if they exist in another object, for example:
let objA = {
x:"1",
y:"2",
z:"3"
};
let objB = {
a:"4",
z:"newValue",
c:"6"
};
I want to get values from objB if the same key exists in objA,
result should be something like that:
rsultObj = {
x:"1",
y:"2",
z:"newValue"
}
You can iterate the keys of objA with Array.forEach(), and replace the value of every key that is found in objB:
const objA = { x: "1", y: "2", z: "3" };
const objB = { a: "4", z: "newValue", c: "6" };
Object.keys(objA).forEach(key => {
if (key in objB) {
objA[key] = objB[key];
}
});
console.log(objA);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With