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

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

本文介绍了如何在数组中查找对象的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON字符串,如:

I have a JSON string as:

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

我通过eval将其转换为对象:

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?

提前谢谢!

推荐答案

如果所有标签都是这样,则可以像这样更改结构,因此我认为它是标签数组",它会更合适.

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"]';

然后使用 JSON.parse 解析它们,或者您正在使用jQuery, $.parseJSON 使其可在更多浏览器上使用:

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现在应该是一个数组,您可以使用 .

labels should now be an array, which you can use Array.indexOf.

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

它是ES5 ,大多数现代浏览器都支持它.对于较旧的浏览器,不幸的是,您需要一个polyfill . .也使用循环.

It's ES5 and most modern browsers support it. For older browsers, you need a polyfill which unfortunately... also uses a loop.

这篇关于如何在数组中查找对象的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:59