【问题标题】:filter an array of objects by property based on where like condition根据 where like 条件按属性过滤对象数组
【发布时间】:2018-09-07 04:24:19
【问题描述】:

我需要过滤特定属性与用户类型匹配的对象数组。

鉴于此

peopleList = [ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "jim foo", age:101},
  {name: "bob wow", age:67},
  {name: "last john", age:43},
]

只要用户输入第一个字符,我就想过滤数组,而不是完全匹配,而是“喜欢的地方”。

我已经检查了这个问题: Filtering array of objects with lodash based on property value

但它只返回一个完全匹配或不返回任何内容。

我可以使用什么 lodash 函数来返回一个对象数组,其中 name 属性与用户输入的查询字符串相匹配,这样如果用户键入“Jo”,就会返回:

[ 
  {name: "john bee", age:23},
  {name: "john woo", age:43},
  {name: "last john", age:43},
]

如果这很重要,我正在使用 Angular。

【问题讨论】:

    标签: angular lodash


    【解决方案1】:

    试试这个

    const peopleList = [ 
      {name: "john bee", age:23},
      {name: "john woo", age:43},
      {name: "jim foo", age:101},
      {name: "bob wow", age:67},
      {name: "last john", age:43},
    ]
    const search = "jo"
    
    cosnt subList = peopleList.filter((person)=>person.name.indexOf(search) > -1)
    

    【讨论】:

      【解决方案2】:

      在 es6 语法中看起来像

      const filteredArray = peopleList.filter( people => people.name.includes(someText) );
      

      【讨论】:

        【解决方案3】:

        这是没有 lodash 和纯 javascript 的工作 sn-p:

        var peopleList = [ 
          {name: "john bee", age:23},
          {name: "john woo", age:43},
          {name: "jim foo", age:101},
          {name: "bob wow", age:67},
          {name: "last john", age:43},
        ];
        
        var result = peopleList.filter(person => person.name.includes("jo"));
        
        console.log(result);

        【讨论】:

        • 我可以在 .ts 文件中使用它吗?我正在从事的大型项目是基于打字稿,而不是我的决定。如果以上不能使用,还有什么替代方法?
        • 是的,为什么不呢,你可以毫无疑问地使用它@nikocraft
        • 我可以添加一个建议,使它更像一个实际的where like 条件,对person.name.toLowerCase() 进行过滤,因为includes() 是区分大小写的,尽管在这种特定情况下,因为所有的名字都是小写的,没关系。
        • 好建议,君考虑到上面的 vivek 代码,我该在哪里提出这个建议?
        猜你喜欢
        • 2018-12-25
        • 2018-07-06
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        • 2021-04-15
        • 2017-03-19
        • 2018-09-27
        相关资源
        最近更新 更多