h.johan h.johan - 1 year ago 61
Javascript Question

Use $each to search multiple rows of arrays in jQuery

We are trying to create an easy "chat-bot" to interact with which will give you an answer based on keywords in your search query.

Example: You type in "Where is the closest bar?" and the bot will give you the answer "Its here bla bla bla".

We are trying to do this through storing the possible keywords and answers through arrays. We managed to run through one array but are not able to run trough them all to see if there is any keywords that fits to another option. How do we do that?

Is using the $each the right way to go?

var search = [
"words":["hey", "bro"],
"result":"Hey man!"
"result":"Other answer"

var query = search.words;
var answer = search.result;

$("#txt").keypress(function(e) {
if(e.which == 13) {

var str = $('#txt').val();

var res = str.toLowerCase();

if (query.some(function(v) { return res.indexOf(v) >= 0; })) {
else {
$('#result').html('Bummer man! You just don\'t yap about Hyper, why are you even here dawg? ');



Answer Source

var search = [{
  "words": ["hey", "bro"],
  "result": "Hey man!"
}, {
  "words": ["ninja", "stuff"],
  "result": "Other answer"

$("#txt").keypress(function(e) {
  if (e.which == 13) {

    var str = $('#txt').val().toLowerCase();
    var found = false;
    $.each(search, function(index, value){
      if(value.words.indexOf(str) !== -1){
        found = true;
        return false;
      $('#result').html('Bummer man! You just don\'t yap about Hyper, why are you even here dawg? ');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt">

<p id="result"></p>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download