【问题标题】:How can search through json data in vue?vue中如何搜索json数据?
【发布时间】:2019-06-21 07:49:52
【问题描述】:

我有一个 json 文件,我渲染到 table ,我有 11 列,如 id , name 等,我想按每一列搜索,但它只适用于一列,当我开始过滤数据时时间例如我按 id 排序,然后我想按名称排序,它崩溃了。

我有用于从 json 渲染数据的 v-for 结构

<div class="document__json" v-for="(item,index) in filteredJson" :key="index" >
  <div class="document__data" :title=item.priority>{{item.priority}}</div>
  <div class="document__data" :title=item.refid_number>{{item.refid_number}}</div>
</div>

我尝试使用 v-model 搜索 json,我发送到数组的每个字母/单词

data() {
  return {
    myJson: json,
    search: []
  };
},

filteredJson: function() {
  let new_json;
  return this.myJson.filter((x) => {
    new_json = x;
    console.log(x);
    for (let i in this.search) {
      console.log(new_json[i])
      console.log(this.search)
      new_json = new_json[i].toLowerCase().match(this.search[i].toLowerCase());
    }
    return new_json
  });
}

<input type="text" v-model="search['priority']" class="document_search">
<input type="text" v-model="search['refid_number']" class="document_search">

我尝试通过与搜索数组中的数据进行比较来过滤 json,但是如果我将按优先级进行搜索,则只有当我也尝试按 refid_number 进行搜索时,它才会用错误填充粉碎: Cannot read property 'refid_number' of null"

【问题讨论】:

  • 我认为你需要一个新的过滤器变量。因为当您在myJson 变量中过滤数据时,该变量中将不存在数据。尝试创建let jsonForFilter = this.myJson 并通过`jsonForFilter`进行过滤。祝你好运。

标签: javascript json vue.js vuejs2


【解决方案1】:

在您的过滤器函数中,首先设置new_json = x(它是一个对象),然后在for循环中您将new_json设置为match结果,这将是一个数组,它不会将成员作为原始对象 (x),因此它会在下一个循环中崩溃。

我猜你需要的是这样的:

return this.myJson.filter((x) => {
    let match = true;
    console.log(x);
    for(let i in this.search){
        console.log(x[i])
        console.log(this.search)
        if(!x[i].toLowerCase().match(this.search[i].toLowerCase())) match = false;
    }
    return match;
});

【讨论】:

  • 但是你能描述一下 if(!x[i].toLowerCase().match(this.search[i].toLowerCase())) match = false;这个,你怎么来的?更重要的是,它是如何工作的?
  • 当然。就像我说的,match 方法在匹配成功时返回一个数组,否则返回 null 。通过将!放在它前面,它会强制将结果转换为相反的布尔值,所以一个数组变成falsenull变成true。所以基本上,if 中的条件转换为“如果匹配失败”。
  • 但是你定义 let match = true - 这意味着所有数据都在这里?由于当你返回匹配时你也返回数据,无法理解这个
  • 也有很多错误,因为我可以使用小写或带有 null 或 object 的字符串,我试图用其他 div 覆盖它但也不起作用
  • 这里的变量match(对不起,名称选择可能会造成混淆)用于告诉“匹配是否仍然成功”。如果任何列不匹配,我设置match = false 来跟踪这个事实。最后,返回match 告诉filter 方法是否应该保留元素x
猜你喜欢
  • 2019-10-04
  • 2015-08-05
  • 2018-09-17
  • 2018-04-20
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多