Reputation: 21275
Say I have an array of objects similar to
[ {name:"value1", action:"U"}, {name:"text2", action:"d"} ]
with many more entries.
I want to look up a value in this, but with a snafu, Say I want to see if any of the words in the list is in the string "I want to look up value1" and return that index number. How might I approach this? This would be running in Node.JS if that matters.
Upvotes: 1
Views: 89
Reputation: 486
As epascarello noted, just doing a simple for loop wrapped up in a function to get that index should do what you are looking for.
var a = [ {name:"value1", action:"U"}, {name:"text2", action:"d"} ];
function getIndex( query, arr ) {
var reg = RegExp( query );
for ( var i = 0, l = arr.length; i < l; i++ ) {
var item = arr[i];
if ( reg.test(item.name) ) return i;
}
return false;
}
var index = getIndex( 'text', a );
If you are looking for other ways to manipulate data, you may want to take a look at underscore.
EDIT: I looked at your initial question a bit incorrectly, also took note of @pimvdb escaping recommendation. This is probably more of what you want.
var a = [ {name:"value1", action:"U"}, {name:"text2", action:"d"} ];
function getIndex( query, arr ) {
query = escape( query );
for ( var i = 0, l = arr.length; i < l; i++ ) {
var item = arr[i],
reg = RegExp( escape(item.name) );
if ( reg.test(query) ) return i;
}
return false;
}
var index = getIndex( 'I want to look up value1', a );
Upvotes: 1