object/pick.jsjavascript
import getPath from './getPath'
import hasPath from './hasPath'
/**
* 创建一个仅包含指定顶层属性的新对象。
* @function pick
* @memberof module:object
* @param {Object} object 原对象
* @param {string[]} keys 要保留的属性名
* @returns {Object} 新对象,不修改原对象
* @throws {TypeError} 参数类型不正确时抛出
*/
function pick(object, keys) {
if (object === null || typeof object !== 'object') throw new TypeError('object must be an object')
if (!Array.isArray(keys) || keys.some(key => typeof key !== 'string')) throw new TypeError('keys must be a string array')
return keys.reduce((result, key) => {
if (hasPath(object, key)) result[key] = getPath(object, key)
return result
}, {})
}
export default pick