How to find the index of an object in an array
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.
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);