Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of an object in an array

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!

like image 278
amol challawar Avatar asked May 15 '13 07:05

amol challawar


2 Answers

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

like image 62
Eric Avatar answered Oct 14 '22 06:10

Eric


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.

like image 33
Joseph Avatar answered Oct 14 '22 08:10

Joseph