如何过滤整个JSONobject?

How to filter the entire JSON object?

我正在尝试使用 VueJS2 和 Wordpress REST [=32] 过滤 Wordpress JSON 数据 object(object 在我的示例中被命名为 'post') =](我在现实世界的例子中有一个自定义 post 类型)。

我可以通过 post object 的标题 属性 成功过滤,但我想知道是否可以让搜索查询过滤整个 post object 而不仅仅是 post.title 属性 因为搜索词可能包含在 object 其他地方找到的关键字,而不仅仅是标题。

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;
      });
  }
});

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

那些对象真的很广泛。我不确定您是否想要搜索 所有内容

一个完全幼稚的方法可能是这样。

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

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

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

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

但这只会搜索 post 的直接属性,而不是子对象。

我认为您想缩小范围。