简体   繁体   English

如何在数组中查找对象的索引

[英]How to find the index of an object in an array

I have a JSON string as: 我有一个JSON字符串:

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

I converted it into an objects by eval: 我通过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 ! 不要用eval解析json! Use JSON.parse . 使用JSON.parse Array.map is a good alternative to looping here: Array.map是循环的一个很好的替代方法:

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 的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: 然后用JSON.parse解析它们,或者因为你使用jQuery, $.parseJSON让它在更多的浏览器上工作:

var labels = JSON.parse(Str);

labels should now be an array, which you can use Array.indexOf . labels现在应该是一个数组,您可以使用Array.indexOf

var index = labels.indexOf('Month');

It's ES5 and most modern browsers support it. 它是ES5 ,大多数现代浏览器都支持它。 For older browsers, you need a polyfill which unfortunately... also uses a loop. 对于较旧的浏览器, 您需要一个polyfill ,不幸的是...也使用循环。

Note: if you want to get a specific item in JSON by its value, I came across this answer and thought about sharing it. 注意:如果你想通过它的值获得JSON中的特定项目,我会遇到这个答案,并考虑分享它。

You can use Array.splice() 你可以使用Array.splice()

First as @elclanrs and @Eric mentioned use JSON.parse(); 首先,@ elclanrs和@Eric提到使用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. 和它的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); 

Use Array.findIndex() when searching by complex condition 在按复杂条件搜索时使用Array.findIndex()

Array.findIndex() Array.findIndex()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM