如何过滤整个JSON对象?

时间:2017-06-29 01:41:05

标签: javascript vuejs2 wordpress-rest-api

我正在尝试使用VueJS2和Wordpress REST API过滤Wordpress JSON数据对象(该对象命名为' post'在我的示例中)(我的真实世界示例中有自定义帖子类型)

我可以通过post对象的title属性成功过滤,但我想知道是否可以让搜索查询过滤ENTIRE post对象而不仅仅是post.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;
      });
  }
});

有谁知道如何编写代码以便查询可以搜索整个对象?谢谢。

1 个答案:

答案 0 :(得分:1)

这些对象非常广泛。我不确定你是否想要搜索所有内容

完全天真的方法可能就是这样。

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

但是,这将返回与键匹配的文本,但它也会搜索所有子对象。

另一种可能的方法是仅搜索作为字符串的对象的那些属性。

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

但那只会搜索帖子的直接属性而不是子对象。

我认为你想缩小你的范围。