Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Am I able to destructure 2 parts of a json objects string value into 2 variables?

I’m using an API to keep track of soccer scores.

Unfortunately in the response object, there isn’t a key for each team’s score, the value is only available in a string like this:

"ft_score": "1 - 0",

It would be very helpful if I could destructure the score into 2 separate variables for each team. Is there any way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t do it directly, because strings are not destructurable, and you can’t apply operations during destructuring (I’ve often wanted to, but at the same time, it would probably make the code unnecessarily complex). You can destructure arrays, objects, and parameter lists (which are conceptually arrays), but not strings.

If you know the string will be in that format, you can use split(" - ") to get an array.

const { ft_score } = theObject;
const [ team1, team2 ] = ft_score.split(" - ");

Or just

const [ team1, team2 ] = theObject.ft_score.split(" - ");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading