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.
_.pick can help
_.pick(source,Object.keys(pattern))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With