pick.js (2106B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isString = require( '@stdlib/assert/is-string' ).isPrimitive; 24 var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; 25 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 26 27 28 // MAIN // 29 30 /** 31 * Returns a partial object copy containing only specified keys. If a key does not exist as an own property in a source object, the key is ignored. 32 * 33 * @param {Object} obj - source object 34 * @param {(string|StringArray)} keys - keys to copy 35 * @throws {TypeError} first argument must be an object 36 * @throws {TypeError} second argument must be either a string or an array of strings 37 * @returns {Object} new object 38 * 39 * @example 40 * var obj1 = { 41 * 'a': 1, 42 * 'b': 2 43 * }; 44 * 45 * var obj2 = pick( obj1, 'b' ); 46 * // returns { 'b': 2 } 47 */ 48 function pick( obj, keys ) { 49 var out; 50 var key; 51 var i; 52 if ( typeof obj !== 'object' || obj === null ) { 53 throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); 54 } 55 out = {}; 56 if ( isString( keys ) ) { 57 if ( hasOwnProp( obj, keys ) ) { 58 out[ keys ] = obj[ keys ]; 59 } 60 return out; 61 } 62 if ( isStringArray( keys ) ) { 63 for ( i = 0; i < keys.length; i++ ) { 64 key = keys[ i ]; 65 if ( hasOwnProp( obj, key ) ) { 66 out[ key ] = obj[ key ]; 67 } 68 } 69 return out; 70 } 71 throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' ); 72 } 73 74 75 // EXPORTS // 76 77 module.exports = pick;