Hi I have a module exports as such.
module.exports = {
"Computer screen": 'phrase1',
"Table height": 'phrase2',
"Temperature": 'phrase3',
};
And importing the file that has this using 'require' into a var called tries. Then I use the following code to search the module.exports. For example if searchQuery was "computer screen" then it would return 'phrase1'.
var tryThis = tries[searchQuery];
My question is how can i modify this so it searches for any line that contains the search query. For example searching 'table' would return 'phrase2'.
Please help :) thanks ahead.
What you're exporting is an object with properties. You can loop through an object's property names using a for-in
loop (which includes all enumerable properties on the object, both own properties and inherited ones) or by using the array from Object.keys
(which only includes own enumerable properties). So then you can use includes
on each property name.
For your specific example, you might use Object.entries
instead (quite recent, but easily polyfilled), since you may want the value; it returns an array of [key, value]
arrays.
You seem to be using ES5 level syntax only, so:
var tryThis;
Object.entries(tries).some(function(entry) {
if (entry[0].includes(searchQuery)) {
tryThis = entry[1];
return true;
}
});
...or perhaps entry[0].toLowerCase().includes(searchQueryLower)
(where you have searchQueryLower = searchQuery.toLowerCase()
) if you want a case-insensitive match.
Live example:
var tries = {
"Computer screen": 'phrase1',
"Table height": 'phrase2',
"Temperature": 'phrase3',
};
var searchQuery = "Table";
var searchQueryLower = searchQuery.toLowerCase();
var tryThis;
Object.entries(tries).some(function(entry) {
if (entry[0].toLowerCase().includes(searchQueryLower)) {
tryThis = entry[1];
return true;
}
});
console.log(tryThis);
In ES2015+ I'd use for-of
and destructuring:
let tryThis;
for (const [key, value] of Object.entries(tries)) {
if (key.toLowerCase().includes(searchQueryLower)) {
tryThis = value;
break;
}
}
Live example:
const tries = {
"Computer screen": 'phrase1',
"Table height": 'phrase2',
"Temperature": 'phrase3',
};
const searchQuery = "Table";
const searchQueryLower = searchQuery.toLowerCase();
let tryThis;
for (const [key, value] of Object.entries(tries)) {
if (key.toLowerCase().includes(searchQueryLower)) {
tryThis = value;
break;
}
}
console.log(tryThis);
You can, of course, shoehorn that into a reduce
call (because any array operation can be shoehorned into a reduce
call), but it doesn't buy you anything (and you can't stop when you find what you're looking for). Similarly it could be done with map
and filter
.