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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16559040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:21:56  来源:igfitidea点击:

How to find the index of an object in an array

javascriptjquery

提问by amol challawar

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!

提前致谢!

回答by Eric

Don't parse json with eval! Use JSON.parse. Array.mapis a good alternative to looping here:

不要用eval! 使用JSON.parse. 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

js小提琴

回答by Joseph

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, $.parseJSONto get it to work on more browsers:

然后用 解析它们JSON.parse,或者因为你使用的是 jQuery,$.parseJSON让它在更多浏览器上工作:

var labels = JSON.parse(Str);

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

labels现在应该是一个数组,您可以使用它Array.indexOf

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

It's ES5and most modern browsers support it. For older browsers, you need a polyfillwhich unfortunately... also uses a loop.

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

回答by Khalil Malki

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);

回答by coderman

Use Array.findIndex() when searching by complex condition

按复杂条件搜索时使用 Array.findIndex()

Array.findIndex()

Array.findIndex()