I am trying to dynamically add categories to JavaScript object from a string. But the problem is that commas inside this string are not recognized as separate items.
So I have this:
var prices = json_graph['offer_prices'].join(','); // that returns for example '2,3,4,5'
Then I want to use this like so:
xAxis: {
categories: [prices]
}
The problem is, that this is recognized as a single item. How can I split this string by commas and add it under categories?
Thanks for your help!
From the fact you’re using
joinon it, I’d say theoffer_pricesproperty is an array. So there’s no need to turn it into a string (but see below, if you have a reason for doing that you haven’t shown):Or if you want to make a copy of it for some reason rather than using the original:
If you have a reason for creating the
pricesstring and really do want to use it for this, you can do that by splitting it apart using the comma as a delimiter, withsplit:Side note: You’ve written
json_graph['offer_prices']and so that’s what I’ve used above, but if you’re literally using that in your code, you can just writejson_graph.offer_pricesinstead if you want, barring some reason you need not to (you might need the string with some tool or something you’re using, I wouldn’t know).