Skip to content Skip to sidebar Skip to footer

Update An Object With Matching Properties And Ignore New Properties

I'm using Typescript and I would like to update an object with another, only on the matching keys. is there a one-liner (i.e. not a custom function that iterates over the keys) t

Solution 1:

const result = Object.keys(objectOne)
    .reduce((init, key) => Object.assign(init, {[key]: objectTwo[key]}) , {});

Solution 2:

I think there is no built-in function to accomplish what you need, rather than a custom one with iterating over keys of the first object and values of the second one:

const objectOne = {
  a: 0,
  b: 0
};

const objectTwo = {
  a: 1,
  b: 1,
  c: 1,
};

const result = Object.keys(objectOne).reduce((all, key) => {

    all[key] = objectTwo[key] || objectOne[key];

    return all;

},{});

console.log(result);

Post a Comment for "Update An Object With Matching Properties And Ignore New Properties"