.filter不是函数

时间:2019-04-01 15:29:47

标签: javascript ecmascript-6 filter functional-programming

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

{
    "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对我不起作用?

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

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

获取错误:

  

.filter不是函数

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

1 个答案:

答案 0 :(得分:1)

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));