JavaScript的发现在一个阵列的特定属性的对象 [英] javascript find an object with specific properties in an array
问题描述
我需要一个扩展现有的code,不能改变它。
有此数组:
I need to make an extension to existing code, can't change it. There's this array:
var availableTags = [
{ label: "Yoga classes", category: "EDUCATIONAL" },
{ label: "Cooking classes", category: "EDUCATIONAL" },
{ label: "Cheese tastings", category: "EDUCATIONAL" },
{ label: "Maker Workshops", category: "PRACTICAL" },
{ label: "Seminars", category: "PRACTICAL" },
//many more of these
];
现在我需要检查,如果在输入框中输入的文本包含在标签,例如之一如果用户输入瑜伽班=> OK,如果瑜伽=> NOK,sdsdf=> NOK等。
Now I need to check if a text entered in an input box is included in one of the labels, e.g. if the user enters "Yoga classes" => OK, if "Yoga" => NOK, "sdsdf" => NOK, etc.
什么是做到这一点的最好方法是什么?我不知道我可以使用Array.indexOf,因为我不知道如何对象传递给函数,我会尝试通过阵列(约40项)循环和比较每个对象。
What is the best way to do this? I am not sure I can use Array.indexOf as I am not sure how to pass the Object to the function, I would try looping through the array (around 40 entries) and compare each object.
推荐答案
您可以使用的 Array.some 方式:
测试数组中某些元素是否通过由提供的函数实现的测试。
Tests whether some element in the array passes the test implemented by the provided function.
那么你的code看起来是这样的:
Then your code would look something like:
var isFound = availableTags.some(function(el) {
return el.label === 'Yoga classes';
});
的注:一些方法有待匀。的
Note: some method needs to be shimmed.
这篇关于JavaScript的发现在一个阵列的特定属性的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!