在React Chart.js2数据集中过滤对象值的数组

时间:2018-08-15 16:32:19

标签: javascript reactjs ecmascript-6 lodash

我正在实现一个仪表板,该仪表板在父组件中具有搜索输入字段,该值作为道具传递给图表组件。 我一直在努力筛选onChange搜索字符串图表中的数据。下面是我的图表设置。

listitems = [{"App_Id":"10426","YearMonth":"201808","App_Name":"XXX- YYY","department":"XXXX","s_name":"Marl"},{"App_Id":"144689","YearMonth":"201808","App_Name":"ttttt","department":"uuuuuu","s_name":"Steveu",}] 
  

状态

 state = {
     data: this.props.listitems,
     filtervalue: ''
  }
  

图表数据

const data = {

labels: this.state.data.map(x => x.App_Id),
datasets: [{
    label: "Bugs",
    data: this.state.data.map(x => x.code_bugs),
    data1: this.state.data.map(x => x.App_Name),
    data2: this.state.data.map(x => x.s_name),
    backgroundColor: 'rgba(255,99,132,0.2)',
    borderColor: 'rgba(255,99,132,1)',
    borderWidth: 1,
    hoverBackgroundColor: 'rgba(255,99,132,0.4)',
    hoverBorderColor: 'rgba(255,99,132,1)'

}]

};

我正在尝试使用过滤器来搜索对象的值并返回一个过滤器对象数组,该数组随后将成为图表的数据。这意味着用户可以交互地查看图表,因为搜索框中的过滤器发生了更改。

以下是我tried with lodash无法正常工作的内容。请建议

_.filter(listname,function(item) {return item.App_Name.lowerCase.indexOf('searchstring')>-1;}

1 个答案:

答案 0 :(得分:1)

这是实现此目标的一种方法。总体而言,由于它是简单的数组过滤,因此还有很多其他的东西。

我还使用可配置的$('#db-search-results').html('search.php');进行了过滤,因此您可以在任何字段上进行过滤。

注意:在这种情况下,无需使用key,因为ES6具有足够的功能来覆盖这一点。

lodash
listItems = [{
  "App_Id": "10426",
  "YearMonth": "201808",
  "App_Name": "XXX- YYY",
  "department": "XXXX",
  "s_name": "Marl"
}, {
  "App_Id": "144689",
  "YearMonth": "201808",
  "App_Name": "ttttt",
  "department": "uuuuuu",
  "s_name": "Steveu",
}]

const filterItems = (appName, key) => listItems.filter(i => i[key].indexOf(appName) >=0)

console.log(filterItems('ttt', 'App_Name'))
console.log(filterItems('XX', 'App_Name'))
console.log(filterItems('Stev', 's_name'))