I have a JSON string as:
var Str="[{ 'label': 'Month'},{ label: 'within'},{ label: 'From'},
{ label: 'Where'},]";
I converted it into an objects by eval:
var tagString = eval(Str);
I want to get the index of month without a loop.
Is there a better way to get the index of an object in an array without using loops?
Thanks in advance!
Don't parse json with eval
! Use JSON.parse
. Array.map
is a good alternative to looping here:
var str = '[{ "label": "Month"}, { "label": "within"}, { "label": "From"}, { "label": "Where"}]';
var data = JSON.parse(str);
var index = data.map(function(d) { return d['label']; }).indexOf('Month')
jsFiddle
If those are all labels, you could change the structure like this, so it's "An array of labels" which, in my opinion, would be more proper.
var Str = '["Month","within","From","Where"]';
Then parse it them with JSON.parse
, or since you are using jQuery, $.parseJSON
to get it to work on more browsers:
var labels = JSON.parse(Str);
labels
should now be an array, which you can use Array.indexOf
.
var index = labels.indexOf('Month');
It's ES5 and most modern browsers support it. For older browsers, you need a polyfill which unfortunately... also uses a loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With