Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active April 6, 2021 23:57
Show Gist options
  • Select an option

  • Save psenger/deae8730da1f905c0461f5f9019fce5d to your computer and use it in GitHub Desktop.

Select an option

Save psenger/deae8730da1f905c0461f5f9019fce5d to your computer and use it in GitHub Desktop.
[Masking / Plucking - Omitting / Copying Keys / Values from an Object Literal into another Object Literal] #LoDash #JavaScript
/**
* mask values from an object (inverse of pluck).
* @param {Object} [obj={}] - an Object, null and undefined return an empty obj literal.
* @param {[String]} [keys=[]] - an array of keys to mask/remove from the object.
* @return {Object}
*/
const mask = (obj = {}, keys = []) => Object.keys(obj).reduce((ac, key) => {
ac[key] = (keys.some((p)=>(p===key))) ? void 0 : obj[key];
return ac;
}, {});
/**
* pluck values from an object.
* @param {Object} [obj={}] - an Object, null and undefined return an empty obj literal.
* @param {[String]} [keys=[]] - an array of keys to plunk from the object.
* @return {Object}
*/
const pluck = (obj = {}, keys = []) => (keys || []).reduce((ac, key) => {
// eslint-disable-next-line no-param-reassign
ac[key] = (obj) ? obj[key] : undefined;
return ac;
}, {});
describe('pluck', () => {
test.each([
['it should return an empty obj literal when undefined is specified for the object', undefined, [], {}],
['it should return an empty obj literal when undefined is specified for the key', {}, undefined, {}],
['it should return an empty obj literal when null is specified for the object', null, [], {}],
['it should return an empty obj literal when null is specified for the key', {}, null, {}],
['it should return an empty obj literal when {} is specified for the object', {}, ['a'], {}],
['it should return an empty obj literal when an empty array is specified for the key', { a: 'hello' }, [], {}],
['it should work with keys that have hyphens', { 'hello-world': true, 'omitted-key': false }, ['hello-world'], { 'hello-world': true }],
['it should work with a pure JSON-able object', { a: true, b: false }, ['a'], { a: true }],
])('%s', (
testname, obj, keys, expectedResult,
) => {
expect.assertions(1);
expect(pluck(obj, keys)).toMatchObject(expectedResult);
});
test('it should work with a object that has a function',()=>{
const obj = { a: function a() { console.log('yes'); }, b: false };
expect(pluck(obj, ['a'])).toHaveProperty('a');
expect(pluck(obj, ['a'])).not.toHaveProperty('b');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment