Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a lodash function to merge two objects and delete properties of one of them if they don't exist in the other?

Consider the following two objects:

const source = {
  foo: 'value',
  bar: 'value',
  baz: 'value'
};

const pattern = {
  foo: '',
  bar: ''
};

_.fn(source, pattern); // { foo: 'value', bar: 'value' }

In this example 'baz' property is deleted because it doesn't exist in the pattern.

like image 484
jstice4all Avatar asked Apr 05 '16 09:04

jstice4all


2 Answers

_.pick can help

_.pick(source,Object.keys(pattern))
like image 114
Jagdish Idhate Avatar answered Sep 29 '22 09:09

Jagdish Idhate


If you want to mutate the original source object for inline key deletion instead of returning a new one, you can do:

_.difference(_.keys(source), _.keys(pattern)).forEach(k => delete source[k])

Or just plain JS:

Object.keys(source)
  .filter(k => Object.keys(pattern).includes(k))
  .forEach(k => delete source[k])

I generally design for immutability, but this approach might be useful if you want to avoid the overhead of allocating a new object, or you have a lot of primitives that would need copying over by value to a fresh object.

like image 20
Lee Benson Avatar answered Sep 29 '22 10:09

Lee Benson