Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.filter is not a function [duplicate]

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?

like image 888
wellhellothere Avatar asked Apr 01 '19 15:04

wellhellothere


People also ask

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

Is not a function JavaScript object?

A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function. When calling a built-in function that expects a callback function argument, which does not exist. When the called function is within a scope that is not accessible.

Is not a function TypeError is not a function?

This is a standard JavaScript error when trying to call a function before it is defined. This error occurs if you try to execute a function that is not initialized or is not initialized correctly. This means that the expression did not return a function object.

How do you filter an object in JavaScript?

JavaScript objects don't have a filter() method, you must first turn the object into an array to use array's filter() method. You can use the Object. keys() function to convert the object's keys into an array, and accumulate the filtered keys into a new object using the reduce() function as shown below.


1 Answers

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));
like image 116
31piy Avatar answered Oct 04 '22 21:10

31piy