按多个属性和值过滤对象数组

时间:2017-06-02 14:08:48

标签: javascript filter

是否可以按多个值过滤对象数组?

在下面的示例中,我可以通过term_ids 5和6过滤它并同时键入car吗?

add_action( 'wp', 'login_current_user' );
    function login_current_user(){
        if ( is_page() && get_the_id() == 863 ){
            if ( isset( $_GET['id'] ) ){
                if ( !is_user_logged_in() ) {
                    $user_id = $_GET['id'];
                    $user = get_user_by( 'id', $user_id );
                    if ( $_GET['token'] == get_user_meta( $user_id, 'temporary_token', true ) ){
                        delete_user_meta( $user_id, 'temporary_token', $_GET['token'] ); 
                        wp_clear_auth_cookie();
                        wp_set_current_user( $user_id, $user->user_login );
                        wp_set_auth_cookie( $user_id, true );
                        do_action( 'wp_login', $user->user_login );
                        if ( is_user_logged_in() ){
                            $redirect_to=site_url() . '/profile';
                            wp_safe_redirect($redirect_to);
                            exit();
                        }
                    }
                }
            }
        }
    }

如果它更容易使用库肯定是最好的。

4 个答案:

答案 0 :(得分:14)

您可以使用Array.filter

执行此操作



var data = [{
    "id": 1,
    "term_id": 5,
    "type": "car"
  },
  {
    "id": 2,
    "term_id": 3,
    "type": "bike"
  },
  {
    "id": 3,
    "term_id": 6,
    "type": "car"
  }
];

var result = data.filter(function(v, i) {
  return ((v["term_id"] == 5 || v["term_id"] == 6) && v.type == "car");
})

console.log(result)




答案 1 :(得分:5)

您可以使用普通的js filter()方法执行此操作,并使用&&来测试这两种情况。



var data = [{"id":1,"term_id":5,"type":"car"},{"id":2,"term_id":3,"type":"bike"},{"id":3,"term_id":6,"type":"car"}];

var result = data.filter(function(e) {
  return [5, 6].includes(e.term_id) && e.type == 'car'
});

console.log(result);




答案 2 :(得分:3)

以下功能将为您提供帮助。

    nestedFilter = (targetArray, filters) => {
          var filterKeys = Object.keys(filters);
          return targetArray.filter(function (eachObj) {
            return filterKeys.every(function (eachKey) {
              if (!filters[eachKey].length) {
                return true; 
              }
              return filters[eachKey].includes(eachObj[eachKey]);
           });
       });
    };

将此功能与如下所述的过滤器一起使用:

var filters = {
    "id": ["3"],
    "term_id": ["6"],
    "type": ["car","bike"]
}

不传递空数组。如果数组中没有值,请在过滤器中跳过该属性。

结果将被过滤数组。

答案 3 :(得分:0)

另一种方法是使用 lodash filter + reduce。

const arr = [{"id":1,"term_id":5,"type":"car"},{"id":2,"term_id":3,"type":"bike"},{"id":3,"term_id":6,"type":"car"}];

const result = [
  {term_id: 5, type: 'car'},
  {term_id: 6, type: 'car'},
].reduce((prev, orCondition) => prev.concat(_.filter(arr, orCondition)), []);

console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>