Skip to content

Commit 3d64aff

Browse files
added: Object.pick method
1 parent 05e83d9 commit 3d64aff

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

objects.js

+12
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,15 @@ export function filter(source, filter) {
7373
)
7474
: source
7575
}
76+
77+
/**
78+
* Generate a new object picking only the properties from a given array
79+
* @param {Object} source - target object
80+
* @param {Array} keys - list of keys that we want to copy over to the new object
81+
* @return {Object} a new object conaining only the keys that we have picked from the keys array list
82+
*/
83+
export function pick(source, keys) {
84+
return isObject(source)
85+
? Object.fromEntries(keys.map((key) => [key, source[key]]))
86+
: source
87+
}

objects.spec.js

+13
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
defineProperties,
55
defineProperty,
66
filter,
7+
pick,
78
} from './objects.js'
89
import { expect } from 'chai'
910

@@ -64,4 +65,16 @@ describe('Objects', function () {
6465
it('filter (null)', () => {
6566
expect(() => filter(null, (key) => key === 'name')).to.not.throw()
6667
})
68+
69+
it('pick', () => {
70+
const source = { name: 'hello', class: 'test' }
71+
const filtered = pick(source, ['name'])
72+
73+
expect(filtered.class).to.be.not.ok
74+
expect(filtered.name).to.be.equal('hello')
75+
})
76+
77+
it('pick (null)', () => {
78+
expect(() => pick(null, ['name'])).to.not.throw()
79+
})
6780
})

0 commit comments

Comments
 (0)