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!
2 Answers 2
From the fact you're using join on it, I'd say the offer_prices property 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):
xAxis: {
categories: json_graph['offer_prices']
}
Or if you want to make a copy of it for some reason rather than using the original:
xAxis: {
categories: json_graph['offer_prices'].slice(0) // slice(0) = shallow copy
}
If you have a reason for creating the prices string and really do want to use it for this, you can do that by splitting it apart using the comma as a delimiter, with split:
xAxis: {
categories: prices.split(',')
}
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 write json_graph.offer_prices instead 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).
1 Comment
categories = prices.split(",");
This will split the categories string into several strings using , as the separator and return them in an array.