UNPKG

json-transformer-node

Version:

Json Transformer Utility. Many times you want to interact with 3rd party services or clients, this utility acts as an adaptor and help you mantain code clean by maintaining only the json mappings

50 lines (39 loc) 1.26 kB
/** * Created by sudhir.m on 23/03/17. */ const {VALUES} = require('./constants'); const getObjectOrArrayFromStringKey = (path, obj) => { if (path === "") { return obj; } path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties path = path.replace(/^\./, ''); // strip a leading dot let pathArray = path.split('.'); for (let i = 0, n = pathArray.length; i < n; ++i) { let currentPath = pathArray[i]; if (typeof obj === "object" && obj.hasOwnProperty(currentPath) && (currentPath in obj)) { obj = obj[currentPath]; } else if (Array.isArray(obj)) { // create nested path for array traversal currentPath = pathArray.slice(i, pathArray.length).join("."); return obj.map((val) => { return getObjectOrArrayFromStringKey(currentPath, val); }) } else { return VALUES.DEFAULT; } } return obj; }; const isNonEmptyArray = (arr) => { return arr && Array.isArray(arr) && arr.length > 0; }; const isNumber = (x) => { return !isNaN(x); }; const utilities = { getObjectOrArrayFromStringKey, isNonEmptyArray, isNumber }; module.exports = utilities;