Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  99] [ 3]  / answers: 1 / hits: 81036  / 11 Years ago, wed, may 15, 2013, 12:00:00

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!


More From » jquery

 Answers
8

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.


[#78226] Monday, May 13, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaliyahcynthiac

Total Points: 91
Total Questions: 94
Total Answers: 119

Location: Vanuatu
Member since Wed, Oct 14, 2020
4 Years ago
;