UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

75 lines (74 loc) 2.26 kB
import { isObject } from '../guards/non-primitives.js'; import { isNumber, isString } from '../guards/primitives.js'; export function convertObjectValues(data, options) { const { keys, convertTo } = options || {}; const _setValueAtPath = (obj, path, convertTo) => { const segments = path.split('.'); let current = obj; segments?.forEach((key, index) => { if (index === segments?.length - 1) { const value = current?.[key]; if (convertTo === 'string' && !isString(value)) { current[key] = String(value); } else if (convertTo === 'number' && !isNumber(value)) { current[key] = Number(value); } } else { if (isObject(current?.[key])) { current = current?.[key]; } else { current[key] = {}; current = current?.[key]; } } }); return obj; }; const _convertValue = (obj) => { let newObj = { ...obj }; keys?.forEach((key) => { newObj = _setValueAtPath(newObj, key, convertTo); }); return newObj; }; if (Array.isArray(data)) { return data?.map(_convertValue); } return _convertValue(data); } export function pickFields(source, keys) { const result = {}; keys?.forEach((key) => { result[key] = source?.[key]; }); return result; } export function deleteFields(source, keys) { const result = {}; for (const key in source) { if (!keys.includes(key)) { result[key] = source?.[key]; } } return result; } export function pickObjectFieldsByCondition(source, condition) { const result = {}; Object.entries(source)?.forEach(([key, value]) => { if (condition(key, value)) { result[key] = value; } }); return result; } export function remapFields(source, fieldMap) { const result = {}; for (const targetKey in fieldMap) { const sourceKey = fieldMap?.[targetKey]; result[targetKey] = source?.[sourceKey]; } return result; }