Search code examples
javascriptvuejs2wordpress-rest-api

How to filter the entire JSON object?


I am trying to filter a Wordpress JSON data object (the object is named 'post' in my example) using VueJS2 and the Wordpress REST API (I have a custom post type in my real world example).

I can successfully filter via the post object's title property, but I was wondering if it was possible to have the search query filter the ENTIRE post object rather than just the post.title property because there a search term may contain keywords that are found elsewhere in the object, not just the title.

JSFIDDLE here

HTML:

<div id="app" class="container" style="padding-top: 2em;">      
  <input v-model="searchText">

  <table class="table table-striped" v-if="posts">
    <thead>
      <tr>
        <th>Title</th>
        <th>Product Type</th>
      </tr>
    </thead>
    <tr v-for="post in itemsSearched">
      <td>{{post.title.rendered}}</td>
      <td>{{post._embedded["wp:term"][1]["0"].name}}</td>
    </tr>
  </table>
</div>

JS:

var vm = new Vue({
  el: '#app',
  data: {
    message: 'hello world',
    searchText: '',
    posts: []
  },
  computed : {
    itemsSearched : function(){
      var self = this;
      if( this.searchText == ''){
        return this.posts;
      } 
      return this.posts.filter(function(post){
        return post.title.rendered.indexOf(self.searchText) >= 0;
      });
    }
  },
  created: function(){
    $.get('https://wordpress-dosstx.c9users.io/wp-json/wp/v2/products/' + '?_embed=true')
      .done(function(data) {
        vm.posts = data;
      });
  }
});

Does anyone know how to write the code so the query can search the entire object? Thank you.


Solution

  • Those objects are really extensive. I'm not sure you would want to search everything.

    A completely naive way to do this might be this.

    return this.posts.filter(function(post){
      return JSON.stringify(post).includes(self.searchText)
    });
    

    However, this will return text that matches keys, but it would search all sub objects as well.

    Another possible way to do it would be to search only those properties of the objects that are strings.

    return this.posts.filter(function(post){
      return Object.keys(post).some(k => {
        return typeof(post[k]) === "string" && post[k].includes(self.searchText)
      })
    });
    

    But that would only search direct properties of the post and not sub objects.

    I think you want to narrow your scope down.