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?
>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(" - ");