Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace an object's key values if they exist in other object?

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"
}
like image 609
Rocket Reus Avatar asked Oct 24 '25 20:10

Rocket Reus


1 Answers

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);
like image 150
Ori Drori Avatar answered Oct 27 '25 10:10

Ori Drori