0
\$\begingroup\$

Here's a small function to check if the property starts with [ or { and parse the value from a sting into JSON or an array. Properties might be a string or intiger also.

import { mapValues } from 'lodash'

export function resolveValues (data) {
  return mapValues(data, item => {
    if (item.match(/^\[/) || item.match(/^\{/)) return JSON.parse(item)
    return item
  })
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The very first concern is what if item just happens to be a string starting with [ or {?

How about instead of testing for [ and {, why not try parsing it? And if it fails, just return as is? This way, you don't need half-hearted checks.

export function resolveValues (data) {
  return mapValues(data, item => {
    try{ return JSON.parse(item) }
    catch (e) { return item; };
  })
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.