【问题标题】:How to filter the entire JSON object?如何过滤整个 JSON 对象?
【发布时间】:2017-12-02 13:25:12
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript vuejs2 wordpress-rest-api


    【解决方案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)
      })
    });
    

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

    我认为你想缩小范围。

    【讨论】:

    • 谢谢。我认为缩小范围更可行!
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    相关资源
    最近更新 更多