amol challawar
amol challawar

Reputation: 1434

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!

Upvotes: 6

Views: 81666

Answers (4)

coderman
coderman

Reputation: 141

Use Array.findIndex() when searching by complex condition

Array.findIndex()

Upvotes: 0

Khalil Malki
Khalil Malki

Reputation: 39

Note: if you want to get a specific item in JSON by its value, I came across this answer and thought about sharing it.

You can use Array.splice()

First as @elclanrs and @Eric mentioned use JSON.parse();

var Str = '[{ "label": "Month"}, { "label": "within"}, { "label": "From"}, { "label": "Where"}]';

var item = JSON.parse(Str);

item = item.splice({label:"Month"},1);

and Its ES5.

See the snippet code here

var Str = '[{ "label": "Month"}, { "label": "within"}, { "label": "From"}, { "label": "Where"}]';
var item = JSON.parse(Str);

item = item.splice({label:"Month"},1);

console.log(item);

Upvotes: 2

Joseph
Joseph

Reputation: 119847

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.

Upvotes: 14

Eric
Eric

Reputation: 97591

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

Upvotes: 27

Related Questions