UNPKG

@hackplan/polaris

Version:

Shopify’s product component library

35 lines (34 loc) 1.12 kB
import { TypeOf } from '../types'; function pickValueAndLength(obj, key) { const keyPaths = key.split('.'); let value = obj; for (const key of keyPaths) { if (!value.hasOwnProperty(key)) { return null; } value = value[key]; } return { keyPaths, value }; } function pick(obj, ...keyPaths) { const flattenedKeypaths = [].concat(...keyPaths); if (obj == null || flattenedKeypaths.length === 0) return {}; return flattenedKeypaths.reduce((acc, key) => { if (typeof key !== TypeOf.String || obj.hasOwnProperty(key)) { return Object.assign({}, acc, { [key]: obj[key] }); } const pickedValues = pickValueAndLength(obj, key); if (pickedValues === null) { return acc; } const { keyPaths, value } = pickedValues; let len = keyPaths.length; let innerObject = { [keyPaths[--len]]: value }; while (len--) { innerObject = { [keyPaths[len]]: innerObject }; } return Object.assign({}, acc, innerObject); }, {}); } export default pick;