41

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"}

}

Why using .filter doesn't work for me?

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

getting the error:

.filter is not a function

What is the suggested alternative with objects?

5
  • 7
    filter works on arrays. Your's isn't an array. When in doubt, always refer to the docs.
    – 31piy
    Commented Apr 1, 2019 at 15:30
  • what is the suggested solution to filter objects? @31piy Commented Apr 1, 2019 at 15:32
  • @wellhellothere fix whatever is giving you an object instead of an array.
    – Kevin B
    Commented Apr 1, 2019 at 15:35
  • I think this is a good Question. Just add a comment that Array.prototype.filter works only of array and therefore you must use some Object.values() or Object.keys() to work with.. Commented Apr 1, 2019 at 15:44
  • @KevinB Can you please help me with your suggestion? stackoverflow.com/questions/55512730/… Commented Apr 4, 2019 at 9:44

1 Answer 1

86

filter is a method on arrays. Since the code you posted contains an object, you're seeing this error. You may want to apply filter after getting all the values from the object using Object.values, like this:

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

4
  • I'll approve your answer (4 min limit). Is this slower than running the same on an array (in terms of performance). Commented Apr 1, 2019 at 15:41
  • @wellhellothere -- it is of course slower since we're first extracting the object's values, and then iterating over those. If you can fix the origin of this code so that it gives you an array instead, that's the recommended fix for it.
    – 31piy
    Commented Apr 1, 2019 at 15:43
  • If you can review this: stackoverflow.com/questions/55512730/… Commented Apr 4, 2019 at 9:44
  • @wellhellothere -- sorry, I don't know php.
    – 31piy
    Commented Apr 4, 2019 at 11:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.