Home > Net >  quickest way to assingn values of keys which are intersection in the target and source object
quickest way to assingn values of keys which are intersection in the target and source object

Time:12-17

I want to assign only those keys which are already present in the target object and not the other keys that are done by the object.assign method.

example
a = { x: 2}
b = {x:3, y:4}

then result = {x:3}

I know there are other ways in past but is there any newer and better ways to do this like in one line?

CodePudding user response:

You can reduce the keys of the target object to a new object by taking the values from the obj if they exist:

const fn = (target, obj) => Object.keys(target)
  .reduce((acc, key) => key in obj 
    ? { ...acc, [key]: obj[key] } 
    : acc
  , {})

const a = { x: 2}
const b = { x:3, y:4 }

const result = fn(a, b)

console.log(result)

CodePudding user response:

I think the fastest way is:

for (let key in b) {
  if (a[key] === undefined) {
    delete b[key];
  }
}
  • Related