Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding compact object method #5572

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions compactObject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Creates an object with all falsey values removed from the original object. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @since 4.17.21
* @category Object
* @param {Object} object The object to compact.
* @returns {Object} Returns the new object of filtered values.
* @example
*
* compact({a: 1, b: 'foo', c: null, e: 0, '': 1, false: NaN})
* // => { a: 1, b: 'foo' }
*/
function compactObject(object) {
if (object == null) {
return {}
}
const result = {}
const entries = Object.entries(object)

for (const [key, value] of entries) {
if (value && key) {
result[key] = value
}
}
return result
}

export default compactObject
15 changes: 15 additions & 0 deletions test/compactObject.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import assert from 'assert';
import compactObject from '../compactObject.js';
import { falseyObject } from './utils.js';

describe('compact', function () {

it('should filter falsey values', function () {
var object = {
'a': 'aa',
'b': 1,
'c': true
};
assert.deepStrictEqual(compactObject(Object.assign({}, object, falseyObject)), object);
});
});
21 changes: 21 additions & 0 deletions test/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,26 @@ var deburredLetters = [
/** Used to provide falsey values to methods. */
var falsey = [, null, undefined, false, 0, NaN, ''];

/** Used to provide falsey key-value pairs to methods */
var falseyObject = {
0: '',
'': 0,
null: '',
'': null,
undefined: '',
'': undefined,
false: '',
'': false,
NaN: '',
'': NaN,
'': '',
0: 0,
null: null,
undefined: undefined,
false: false,
NaN: NaN
}

/** Used to specify the emoji style glyph variant of characters. */
var emojiVar = '\ufe0f';

Expand Down Expand Up @@ -766,6 +786,7 @@ export {
comboMarks,
deburredLetters,
falsey,
falseyObject,
emojiVar,
empties,
errors,
Expand Down