File tree 2 files changed +25
-0
lines changed
2 files changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -73,3 +73,15 @@ export function filter(source, filter) {
73
73
)
74
74
: source
75
75
}
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
+ }
Original file line number Diff line number Diff line change 4
4
defineProperties ,
5
5
defineProperty ,
6
6
filter ,
7
+ pick ,
7
8
} from './objects.js'
8
9
import { expect } from 'chai'
9
10
@@ -64,4 +65,16 @@ describe('Objects', function () {
64
65
it ( 'filter (null)' , ( ) => {
65
66
expect ( ( ) => filter ( null , ( key ) => key === 'name' ) ) . to . not . throw ( )
66
67
} )
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
+ } )
67
80
} )
You can’t perform that action at this time.
0 commit comments