javascript在数组中查找具有特定属性的对象 [英] javascript find an object with specific properties in an array

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

问题描述

我需要对现有代码进行扩展,无法更改.有这个数组:

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

现在我需要检查输入框中输入的文本是否包含在标签之一中,例如如果用户输入Yoga classes"=> OK,如果Yoga"=> 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.

那么您的代码将类似于:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆