javascript find an object with specific properties in an array
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 ];
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.
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.
Answers
You can use
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:
You need to loop over every item in availableTags and check whether that item's label is equal to some input. Try something like this:
var input = "Yoga classes"; var found = false; for (var i = 0, j = availableTags.length; i < j; i++) { var cur = availableTags[i]; if (cur.label === input) { found = true; break; } } console.log(found);
DEMO: http://jsfiddle.net/k4cp4/4/
Where this can easily be put into a function, like:
var checkMatch = (function () { 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" } ]; return function (input) { var found = false; for (var i = 0, j = availableTags.length; i < j; i++) { var cur = availableTags[i]; if (cur.label === input) { found = true; break; } } return found; }; })();
DEMO: http://jsfiddle.net/k4cp4/5/
This checks for an exact match. So if you want a case insensitive match, you can use:
if (cur.label.toLowerCase() === input.toLowerCase()) {
DEMO: http://jsfiddle.net/k4cp4/6/
If you want to see if any of the labels contain the input, you can use indexOf like:
if (cur.label.indexOf(input) > -1) {
DEMO: http://jsfiddle.net/k4cp4/7/