【问题标题】:Filter an array by key and value by accessing an array通过访问数组按键和值过滤数组
【发布时间】:2018-09-02 20:59:55
【问题描述】:

如何从数组中的键和值中过滤数组?

我需要通过数组中的键和值来过滤数组中的项目,这个键将始终包含布尔值。

我知道有一些方法可以做到这一点,但我想要一个更推荐的方法来做到这一点,因为当记录太多时,这会影响过滤器性能。

[
      {name: 'PERSON1', 
      info_add: {name: 'obs', active: true, faithful: false}.........},

      {name: 'PERSON2', 
      info_add: {name: 'obs', active: true, faithful: true}.........},

      {name: 'PERSON3', 
      info_add: {name: 'obs', active: false, faithful: true}.........},
]

如果值为 false 或 true,我需要通过 active 键或 faithful 键放入 info_add

active = true => PERSON1 对象,PERSON2 对象

active = false => PERSON3 对象

faithful = true => PERSON2 对象,PERSON3 对象

faithful = false => PERSON1 对象

由于我的数组非常大,而且里面还有其他数组,我想知道如何最好地过滤来自activefaithful 的对象。

目前我只是用下面的方法过滤字符串值,但我想创建另一种方法来提高过滤器性能。

public static filterArrayByString(mainArr, searchText)
{
    if ( searchText === '' )
    {
        return mainArr;
    }

    searchText = searchText.toLowerCase();

    return mainArr.filter(itemObj => {
        console.log(itemObj);
        return this.searchInObj(itemObj, searchText);
    });
}

【问题讨论】:

    标签: arrays angular typescript arraylist filter


    【解决方案1】:
    const _ = require('lodash');
    
    var arr = [
    {
        name: 'PERSON1',
        info_add: {name: 'obs', active: true, faithful: false}
    },
    {
        name: 'PERSON2',
        info_add: {name: 'obs', active: true, faithful: true}
    },
    
    {
        name: 'PERSON3',
        info_add: {name: 'obs', active: false, faithful: true}
    }];
    
    var activeFiltered = _.filter(arr, function(person){
        return person.info_add.active;
    });
    
    var faithfulFiltered = _.filter(arr, function(person){
        return person.info_add.faithful;
    });
    
    console.log(activeFiltered);
    console.log(faithfulFiltered);
    

    您可以使用 lodash 使用 filter 函数在数组上轻松应用过滤器。 第一行就是NodeJS使用lodash的方式,其余的都一样。

    在过滤器函数的回调函数中,可以单独访问数组中的每个项目,以确定该项目是否应该在过滤后的数组中。 返回 true 表示将包含项目,返回 false 表示将不包含项目。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2012-09-23
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多