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

Time:02-02

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?

CodePudding user response:

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

CodePudding user response:

var score = '1 - 0';
var arr = score.split(" - ");

var team_1 = arr[0];
var team_2 = arr[1];

try something like that.

CodePudding user response:

Firstly, this question has nothing to do with JSON. It is about processing strings like "1 – 0"; where those strings come from is irrelevant.

JavaScript destructuring applies to objects and arrays. Actually, strings can be treated as arrays, so destructuring can be applied to strings too. But not in the sense that you want!

For your purposes, you need to convert the string into an appropriate object or array. The straightforward way of doing that, as stated in the other answers, is to use String#split():

const [score1, score2] = ft_score.split(' - ');

Replace ft_score with apiResponse.ft_score or whatever is appropriate.

  •  Tags:  
  • Related