【问题标题】:lodash multi param in react nativelodash 多参数反应原生
【发布时间】:2020-07-29 21:45:42
【问题描述】:

我有一个数组,我想在它上面应用一些过滤器。 我正在使用 lodash tovdo 这个。但我不知道如何将我的状态值添加到条件中

 this.state = {
        TargetAge : [23 , 101],
        TargetId : [1 ,2],
        TargetName : ['john' , 'bob'],
        TargetStart : '2020-03-19 14:12:30',
        TargetStop: '2020-09-19 14:12:30'

    }
    const myArr = [ {name: "john", age: 23, id: 1, start: '2020-07-19 14:12:30', stop: '2020-08-19 14:12:30'},
                    {name: "john", age: 43,  id: 2, start: '2020-05-19 14:12:30', stop: '2020-09-19 14:12:30'},
                    {name: "jim", age: 101, id: 3, start: '2020-04-19 14:12:30', stop: '2020-06-19 14:12:30'},
                    {name: "bob", age: 67, id: 4, start: '2020-03-19 14:12:30', stop: '2020-07-19 14:12:30'} ];
  

在这种情况下,我尝试使用

 let tmp = _.filter(myArr, x => x.id == 1 || x.id == 2 );
 console.log(tmp) // god result for id but targetId can be empty

 let tmp = _.filter(myArr, x => x.id == targetId );
     console.log(tmp) // bad result

如何添加 0 或 X 参数来过滤我的数组?

预期输出:

if this.state.TargetId == [1, 2] && this.state.TargetAge = [23] // in this case other state are empty
 res = [ {name: "john", age: 23, id: 1, start: '2020-07-19 14:12:30', stop: '2020-08-19 14:12:30'}}




if  this.state.TargetStart == '020-04-19 14:12:30'  && this.state.TargetStop = '2020-08-19 14:12:30 // in this case other state are empty 
 res == [ {name: "john", age: 23, id: 1, start: '2020-07-19 14:12:30', stop: '2020-08-19 14:12:30'},
          {name: "jim", age: 101, id: 3, start: '2020-04-19 14:12:30', stop: '2020-06-19 14:12:30'} ]
                   

【问题讨论】:

  • 你能添加你的预期输出吗?
  • 您的代码不清楚:您的意思是 `let tmp = _.filter(myArr, x => x.id == this.state.TargetId);` 给出的结果不好?跨度>
  • 是的,我的 console.log(tmp) // 不好的结果; tmp 为空
  • this.state 是动态的吧?你应该在 this.state 和 myArr 中有相同的键来过滤。

标签: javascript react-native lodash


【解决方案1】:

我很确定你很接近,你只需要稍微改变一下功能。

// Your current code:
let tmp = _.filter(myArr, x => x.id == targetId );
     console.log(tmp) // bad result

// What I am pretty sure you want:
let tmp = _.filter(myArr, x => _.includes(this.state.TargetId, x.id));
     console.log(tmp)

【讨论】:

    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 2017-02-20
    相关资源
    最近更新 更多