\$\begingroup\$
\$\endgroup\$
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
})
}
asked Apr 26, 2016 at 0:24
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
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; };
})
}
answered Apr 26, 2016 at 2:05
default