.filter 不是函数 [英] .filter is not a function

查看:36
本文介绍了.filter 不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的对象(确保它是一个 typeof 对象):

This is my object (made sure it's a typeof object):

{
    "1": {"user_id":1,"test":"","user_name":"potato0","isok":"true"},

    "2":{"user_id":2,"test":"","user_name":"potato1","isok":" true"},

    "3":{"user_id":3,"test":"","user_name":"potato2","isok":" true"},

    "4":{"user_id":4,"test":"","user_name":"potato3","isok":"locationd"}

}

为什么使用 .filter 对我不起作用?

Why using .filter doesn't work for me?

是不是因为我的变量是 typeof object 并且该方法仅适用于数组?

Is it because my variable is typeof object and the method works only with arrays?

this.activeUsers = window.users.filter( function(user) {
     // return ( (user.test === '0') && (user.isok === '0') ); 
     return user.user_id === 1;
}); 

出现错误:

.filter 不是函数

.filter is not a function

建议的对象替代方案是什么?

What is the suggested alternative with objects?

推荐答案

filter 是一个数组方法.由于您发布的代码包含一个对象,因此您会看到此错误.您可能希望在使用 Object.values,像这样:

var users = {
  "1": {
    "user_id": 1,
    "test": "",
    "user_name": "potato0",
    "isok": "true"
  },

  "2": {
    "user_id": 2,
    "test": "",
    "user_name": "potato1",
    "isok": " true"
  },

  "3": {
    "user_id": 3,
    "test": "",
    "user_name": "potato2",
    "isok": " true"
  },

  "4": {
    "user_id": 4,
    "test": "",
    "user_name": "potato3",
    "isok": "locationd"
  }
};

console.log(Object.values(users).filter(user => user.user_id === 1));

这篇关于.filter 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆