javascript 使用字符串搜索对任何属性过滤JSON数组:类型脚本

bxfogqkk  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(124)

我有一个Json对象数组,我将它绑定到一个网格。

一月一日

这是我的示例JSON

[{
      "TransactionID": "1",
      "MyProperty1": "some data 1",
      "MyProperty2": "28-02-2023",
      "MyProperty3": "some more data 1",
      "MyProperty4": "some other data 1",
      "documents": [
                      {"TransactionID": "1","MyProperty1":"Document 1","MyProperty2":"Completed"},
                      {"TransactionID": "1","MyProperty1":"Document 2","MyProperty2":"In Progress"},
                      {"TransactionID": "1","MyProperty1":"Document 3","MyProperty2":"In Progress"}
                   ]
    }, 
    {
      "TransactionID": "2",
      "MyProperty1": "some data 2",
      "MyProperty1": "27-02-2023",
      "MyProperty1": "some more data 2",
      "MyProperty1": "some other data 2",
      "documents":  [ 
                       {"TransactionID": "2","MyProperty1":"Document 1","MyProperty1":"Completed"},
                       {"TransactionID": "2","MyProperty1":"Document 2","MyProperty1":"Completed"}
                    ]
    }];

我尝试过这样做,但抛出此错误'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'

doFilter(filterText: string) {
    
   let filteredObject = this.engagementData.filter(o =>
      Object.keys(o).some(k => o[k].toLowerCase().includes(filterText.toLowerCase())));
       
  }

这里我的数据包含上面的JSON。
有人能告诉我我错过了什么吗?
我知道循环遍历每个JSON对象的每个属性是一种选择
但如果有任何内置函数可以从JSON中检索所有对象(在对象的任何属性中具有特定字符串),则会很有帮助

pdkcd3nj

pdkcd3nj2#

如果你的this.engagementDataobject类型,那么你不能在它上面调用string方法,所以你不能在它上面调用.toLowerCase(),这就是错误告诉你的。
如果您试图过滤objects,它具有与您搜索的文本匹配的属性,那么您应该检查该object的所有values

let filteredObject = this.engagementData.filter(o =>
    Object.keys(o).some(k => Object.values(o[k]).some(val => val.toLowerCase().includes(filterText.toLowerCase())));

您需要对o[k]对象properties的每个值调用toLowerCase().includes(),而不是o[k]

注:

对于object类型就是这种情况,如果o[k]可以是array类型或其他类型,则需要检查o[k]的类型并为此修改代码。

相关问题