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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.