UNPKG

ice.fo.utils

Version:

74 lines (64 loc) 2.08 kB
/* eslint-disable vue/max-len */ import _get from 'lodash/get'; import _set from 'lodash/set'; import parseDataMap from '../Parse/parseDataMap'; function get(o, key, defaultV) { const result = _get(o, key, defaultV); return result != null ? result : defaultV; } export function getValue(o, defaultValue = '', path = '') { if (path) { const paths = path.split('.'); return _get(o, paths.concat('value')) || _get(o, paths) || defaultValue; } if (!o) { return defaultValue; } return (o.value !== undefined ? o.value : Object.keys(o).length ? o : null) || defaultValue; } /** * Map a list of items with new properties path changes. * * @example * [{ name: 'nikochin', age: 10 }, { name: 'steve', age: 20 }]; // return [{ fullName: 'nikochin', legalAge: 10 }, { fullName: 'steve', legalAge: 20 }] * * @param {object} dataMapConfig * @param {object[]} items * @param {VueContext} context * @returns */ export default function mapData(dataMapConfig, items, context = { strict: false }) { const parseValues = context; const mapPaths = (dataMapConfig.list || dataMapConfig.binding || []).filter((i) => i.toField && (i.fromField || i.format)); const result = items.filter((i) => i).map((i) => { const resultItem = { ...(context.strict ? {} : i), key: `${i.id || Math.random()}_${get(context, '$i18n.locale', '')}`, ranKey: Math.random(), id: i.id, get item() { return this; }, get data() { const data = {}; for (const k in this) { if (!['id', 'key', 'ranKey', 'item', 'data'].includes(k)) { data[k] = this[k]; } } return data; }, }; const data = { ...resultItem, ...parseValues, ...i, }; mapPaths.forEach(({ fromField, toField, format }) => { fromField = (fromField || '').trim(); format = getValue(format).trim().split('>').pop(); _set(resultItem, toField, parseDataMap({ data, from: fromField, format })); }); return resultItem; }); return result; }