Skip to content

Commit

Permalink
added: Object.pick method
Browse files Browse the repository at this point in the history
  • Loading branch information
GianlucaGuarini committed Jun 21, 2024
1 parent 05e83d9 commit 3d64aff
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
12 changes: 12 additions & 0 deletions objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,15 @@ export function filter(source, filter) {
)
: source
}

/**
* Generate a new object picking only the properties from a given array
* @param {Object} source - target object
* @param {Array} keys - list of keys that we want to copy over to the new object
* @return {Object} a new object conaining only the keys that we have picked from the keys array list
*/
export function pick(source, keys) {
return isObject(source)
? Object.fromEntries(keys.map((key) => [key, source[key]]))
: source
}
13 changes: 13 additions & 0 deletions objects.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
defineProperties,
defineProperty,
filter,
pick,
} from './objects.js'
import { expect } from 'chai'

Expand Down Expand Up @@ -64,4 +65,16 @@ describe('Objects', function () {
it('filter (null)', () => {
expect(() => filter(null, (key) => key === 'name')).to.not.throw()
})

it('pick', () => {
const source = { name: 'hello', class: 'test' }
const filtered = pick(source, ['name'])

expect(filtered.class).to.be.not.ok
expect(filtered.name).to.be.equal('hello')
})

it('pick (null)', () => {
expect(() => pick(null, ['name'])).to.not.throw()
})
})

0 comments on commit 3d64aff

Please sign in to comment.