【问题标题】:Filter array of Object values in React chartjs2 dataset在 React chartjs2 数据集中过滤对象值数组
【发布时间】:2019-01-22 13:40:33
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs ecmascript-6 lodash


    【解决方案1】:

    这是实现这一目标的一种方法。总的来说,其他的不多,因为它是一个简单的数组过滤。

    我还使用可配置的key 制作了过滤器,因此您可以过滤任何字段。

    注意:在这种情况下无需使用lodash,因为 ES6 已经足以涵盖这一点。

    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'))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 2020-01-17
      • 2019-05-03
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多