kayduh kayduh - 4 months ago 8
Javascript Question

Retrieving data from JSON object using substring

If i have the following JSON object:

taxcodes = {
"CA_MONO CO": {
"Rate": 1,
"Country": "United States"
}
}


Using
taxcodes["CA_MONO CO"].Rate
works perfectly in retrieving the rate of
1
.

Now my issue is, if i had a variable lets say:
x = "CA_MONO CO_MAMMOTH LAKES"
.

taxcodes[x].Rate
will not work obviously because of the
_MAMMOTH LAKES
.

So what I did was cut all strings after
CO_
, which gave me
CA_MONO
then added
' CO'
back on to the end of the string which gave me
CA_MONO CO
.

var modifiedx = x.substring(0, x.indexOf('CO_')) + ' CO';


I then attempted to pull the data using
taxcodes[modifiedx].Rate
, which did not pull the data.

Answer

You have an extra space when you append the + ' CO'

taxcodes = {
   "CA_MONO CO": {
          "Rate": 1,
          "Country": "United States"
       }
}

x = "CA_MONO CO_MAMMOTH LAKES"

var modifiedx = x.substring(0, x.indexOf('CO_')) + 'CO';

console.log(
	taxcodes[modifiedx].Rate
);