user4676340
user4676340

Reputation:

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.

// Destination
objectOne = {
  a: 0,
  b: 0,
};

// Source
objectTwo = {
  a: 1,
  b: 1,
  c: 1,
};

// Expected
result = {
  a: 1,
  b: 1,
};

// Current solution
const current = {};
Object.keys(objectTwo).forEach(key => key in objectOne ? current[key] = objectTwo[key] : null);

console.log(current);

is there a one-liner (i.e. not a custom function that iterates over the keys) that would ignore the property c in the source ? I would also like to avoid using libraries such as lodash or JQuery.

Duplicate EDIT my question isn't about merging two objects, my question is about ignoring the fields in the second object, that aren't in the first object.

Upvotes: 10

Views: 4024

Answers (3)

user4676340
user4676340

Reputation:

After a while without answers, it seems the shortest solution is the one I provided myself :

Object.keys(newObj).forEach(key => key in oldObj? result[key] = newObj[key] : null)

Upvotes: 6

Leonid Pyrlia
Leonid Pyrlia

Reputation: 1712

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);

Upvotes: 0

Reuven Chacha
Reuven Chacha

Reputation: 889

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

Upvotes: 0

Related Questions