Building updatable list from API

Building updatable list from API

east1999east1999 Posts: 31Questions: 11Answers: 0

After getting some help in this forum, I was able to build charts that update in real time with search on my table.

Now, I'd like to add something else next to these charts. What I want is to grab all the keywords for each row (in the hidden column "keywords"), count them, and make a list like:

  • Places (30)
  • Travels (20)
  • People (10)
  • Etc.

This would be connected to the table, so I would get an updated list of keywords linked to those entries and numbers for how many times they occur.

I have already coded a function that operates in a similar way: it extracts the keywords and builds a select form. However, the only way I achieved this was by initiating a new JSON call after DT loads, which is really slow. I would like to use the API but right off the gate it uses different kinds of objects and I can't build a string from them when I use var data = $('#mytable').DataTable().columns('keywords')rows({search: 'applied'}).data();.

Here's my current code:

`$.getJSON("index.json", function(jsonData) {
  var types = {};
  jsonData.forEach(function(item) {
    if (!types[item.keyword]) {
      types[item.keyword] = 0;
    }
    types[item.keyword]++;
  });

  var keywordsCountObject = {};
  for (var typeKey in types) {
    var keywordItemsToCount = typeKey.toString().split(", ");

    keywordItemsToCount.forEach(function(itemToCount) {
   //   console.log(itemToCount);
      if (!keywordsCountObject.hasOwnProperty(itemToCount)) {
        keywordsCountObject[itemToCount] = 1;
      } else {
        keywordsCountObject[itemToCount]++;
      }      
    });
  }

    for (var prop in keywordsCountObject) {
      var o = new Option(prop + '(' + keywordsCountObject[prop].toString() + ')', prop);
      /// jquerify the DOM object 'o' so we can use the html method
      $(o).html(prop + ' (' + keywordsCountObject[prop].toString() + ')');
      $("#tagselect").append(o);

      $( "option", ".custom-select" ).sort(function( a, b ) {
      return $( a ).text() > $( b ).text();    
      }).appendTo( ".custom-select" );
    
      };});

    $("#tagselect").change( function() {
      var table = $('#bdphct').DataTable();  
      table.columns(6).search( this.value ).draw();
      alert("click!");
      });`

Answers

  • kthorngrenkthorngren Posts: 20,332Questions: 26Answers: 4,774

    Its way too early to look through your code :wink:

    Since you have the keyword object in your JSON response it is available via the API's; pluck() and toArray(). For example:

      var keywords = table
        .rows()
        .data()
        .pluck( "keyword" )
        .toArray();
    

    This will result in an array of keywords from each row. You can then count them, etc. Here is an example I built for something else that will show you how it works:
    http://live.datatables.net/sowidusi/2/edit

    Kevin

This discussion has been closed.