Utils/convertParameters.js

/**
 * Recursive method that will convert all string values in an object to a more
 * appropriate type.
 *
 * In MV there are a lot of objects filled with strings of different values, a lot
 * of times we need to convert each value manually, instead use this to quickly
 * deep parse each value from string to the correct type.
 *
 * @function convertParameters
 * @since 1.0.0
 * @memberof module:Utils
 *
 * @param {object} parameters - The string filled object you want converted
 *
 * @returns An object with it's string values converted
 * @example
 *
 * const myParams = { p1: '22', p2: 'true' }
 * convertParameters(myParams) // => { p1: 22, p2: true }
 *
 * const myParams = { p1: '{a: 1'1, c: '2'}', p2: '[{}, {}, {}]' }
 * convertParameters(myParams) // => { p1: {a: 1, c: 2}, p2: [{}, {}, {}] }
 *
 */
export default function convertParameters (parameters) {
  const _isBoolean = (string) => string === 'true' || string === 'false'

  const _isJson = function (text) {
    try {
      const parsed = JSON.parse(text)
      if (parsed && (typeof parsed === 'object' || Array.isArray(parsed))) {
        return parsed
      }
    } catch (error) { }
    return false
  }

  const result = {}

  Object.keys(parameters).forEach(key => {
    const parameter = parameters[key]
    if (parameter === '') {
      result[key] = ''
    } else if (isFinite(parameter)) {
      result[key] = Number(parameter)
    } else if (_isBoolean(parameter)) {
      result[key] = JSON.parse(parameter)
    } else if (Array.isArray(parameter)) {
      result[key] = Array.from(parameter)
    } else if (_isJson(parameter)) {
      result[key] = convertParameters(JSON.parse(parameter))
    } else {
      result[key] = parameter
    }
  })
  return result
}