Fred J. Fred J. - 5 months ago 22
Javascript Question

Live filtering of json

This Meteor client app "mostly smartPhone usage" needs to accept input from user in the form of typed text and filter json data of about 500 bottom nodes, giving back the branches of the tree where the bottom node text contains the user input text.

{
"people": {
"honour": [
[
"family"
],
[
"friends"
]
],
"respect": [
[
"one another"
]
]
},
"animals": {
"eat": [
[
"row food"
]
]
}
}


When the user inputs 'a', the code needs to give the tree where the occurrence exists:

people, honour, family.

people, respect, one another

When the user types 'o', output should be:

people, respect, one another.

animals, eat, row food.

When the user types 'oo', output should be:

animals, eat, row food.

when the user types 'f', output should be:

people, honour, family.

people, honour, friends.

animals, eat, row food.

My options are:


  1. Converting the json to javascript object and write the seach/find/match logic with few loops.

  2. Use defiantjs which I never used before and have to learn.

  3. Import the json to mongodb and filter the database.

  4. Whatever else you suggest.



Which would be best fit for fast results and easy of maintenance? Thanks

Answer

I think a few loops would work just fine. In the example below, as you type in the input, the results matching your search are logged to the console.

$("#search").on("input", function() {
  var result = [];
  var search = this.value;

  if (search.length) {
    $.each(data, function(key1, value1) {
      //key1: people, animals
      $.each(value1, function(key2, value2) {
        //key2: honor, respect, eat
        $.each(value2, function(i, leaf) {
          if (leaf.length && leaf[0].indexOf(search) >= 0) {
            //found a match, push it onto the result
            var obj = {};
            obj[key1] = {};
            obj[key1][key2] = leaf;
            result.push(obj);
          }
        });
      });
    });
  }

  console.log(result);
});

var data = {
  "people": {
    "honour": [
      [
        "family"
      ],
      [
        "friends"
      ]
    ],
    "respect": [
      [
        "one another"
      ]
    ]
  },
  "animals": {
    "eat": [
      [
        "row food"
      ]
    ]
  }
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="search" />