Javascript filter для object

JavaScript filter object type tutorial

Unlike JavaScript array type, the JavaScript object type doesn’t have a filter() method. When you need to filter object type data, you need to create your own helper function.

No matter which value you want to use to filter the object , you need to use a combination of Object.entries() , Array.filter() and Object.fromEntries() methods to perform the filtering.

First, you need to transform the object type you have into an array using Object.entries() method. The method accepts an object parameter and transforms it into a two-dimensional array:

The value of scoreArr will be an array as follows:
Now that you have an array representing the object, you can use the Array.filter() method to filter this array. For example, the code below will remove an element with the key "Jack" and return the rest:
 The filteredArr value will be as follows:
Now that the array has all the elements you wanted, you need to transform the array back into an object by using Object.entries() method. The method will transform an array of key/value pairs into an object:

And that’s how you filter an object by its key value.

Читайте также:  Create new list kotlin

Filter an object by its property value

When you want to filter an object by its property value, you need to use the same methods you just need to change the condition inside the filter() method to filter by the property value.

For example, the code below will include only properties with a value of more than 7:

As you can see from the code above, you can change the filter by property value by simply changing the filter() condition. Feel free to use and modify the code example above to meet your requirement 😉

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

How to Filter an Object with JavaScript

JavaScript’s array filter() function is a handy function that takes a function callback and returns a new array with just the elements for which callback returned true .

const numbers = [1, 2, 3, 4, 5, 6]; let callback = v => v % 2 === 0; const even = numbers.filter(callback); even; // [2, 4, 6] callback = v => v % 2 === 1; const odd = numbers.filter(callback); odd; // [1, 3, 5]

Unfortunately, JavaScript objects don’t have a filter() function. But that doesn’t mean you can’t use filter() to filter objects, you just need to be able to iterate over an object and convert the object into an array using Object.entries() .

const obj = < name: 'Luke Skywalker', title: 'Jedi Knight', age: 23 >; // Convert `obj` to a key/value array // `[['name', 'Luke Skywalker'], ['title', 'Jedi Knight'], . ]` const asArray = Object.entries(obj); const filtered = asArray.filter((Javascript filter для object) => typeof value === 'string'); // Convert the key/value array back to an object: // `< name: 'Luke Skywalker', title: 'Jedi Knight' >` const justStrings = Object.fromEntries(filtered);

You can implement this logic as a one-liner, but it is a bit messy:

function filterObject(obj, callback) < return Object.fromEntries(Object.entries(obj). filter((Javascript filter для object) => callback(val, key))); >

You can implement this more elegantly using Lodash’s flow() function, which behaves like a pipe() function that lets you chain static methods like Object.fromEntries() and Object.entries() .

const numWins = < 'BUF': 11, 'MIA': 9, 'NE': 6, 'NYJ': 1 >; const atLeast9Wins = _.flow([ Object.entries, arr => arr.filter((Javascript filter для object) => value >= 9), Object.fromEntries ])(numWins); atLeast9Wins; // 

More Fundamentals Tutorials

Источник

How to Filter an Object by Key in JavaScript

JavaScript’s Objects are not iterable like arrays or strings, so we can’t make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.

If you’d like to read more about the filter() method — read our Guide to JavaScript’s filter() Method!

In this article, we will explore how to filter an Object making use of its key in JavaScript.

An object is, essentially, a map of properties and their values. This key-value pair set is what an object is. We can naturally extract the keys and values individually:

Keys are extracted using Object.keys() , while values are extracted using Object.values() . To retrieve both keys and values, you may alternatively use Object.entries() . We are solely concerned with the keys in this article, for filtering keys against certain criteria.

Using Object.keys() to filter an Object

The Object.keys() method is used to generate an array whose elements are strings containing the names (keys) of an object’s properties. The object is passed as an argument to Object.keys() :

For example, suppose we have an object of user scores in various subjects:

const userScores = < chemistry: 60, mathematics: 70, physics: 80, english: 98 >; 

We can loop through the object and fetch the keys, which for this example would be the subjects:

const names = Object.keys(userScores); console.log(names); // ["chemistry","mathematics","physics","english"] 

After you’ve generated the keys, you may use filter() to loop over the existing values and return just those that meet the specified criteria. Finally, you can use reduce() to collect the filtered keys and their values into a new object, for instance.

Note: filter() is great at chaining with other functional methods!

Assume we have an Object, and we want to return only key-value pairs with the word «name» in the keys:

We could filter by making use of the Objects key:

const names = Object.keys(user) .filter((key) => key.includes("Name")) .reduce((obj, key) => < return Object.assign(obj, < Javascript filter для object: userJavascript filter для object >); >, <>); console.log(names); 

We made use of Object.keys(user) to generate all the keys as an array, resulting in an array:

["firstName","lastName","userName","email","age","hobby"] 

We then used the array function includes() as the criteria, within the filter() method, to go over each element in the array to determine whether any key included the word «Name»:

["firstName","lastName","userName"] 

Then, we made use of reduce() to reduce the array down into an object.

Note: The reduce() function accepts two arguments: an object as the first parameter (identity) and the current iteration value as the second.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

We are using Object.assign() to combine source objects into a target object in the new object being generated. The Object.assign() function takes the Object that is being built and adds the current key-value pair that we are passing into it.

And at the end of this — we have a new object, filtered by the keys:

< firstName: 'John', lastName: 'Doe', userName: 'johndoe12' > 

Filter Array of Objects by Key

Oftentimes, the objects we’re processing are sequenced in an array. Filtering each is as easy as filtering one — we just iterate through the array and apply the same steps:

const users = < John: < username: 'johncam112', age:19 >, Daniel: < key: 'Dandandel1', age:21 >, Ruth: < key: 'rutie01', age:24 >, Joe: < key: 'Joemathuel', age:28 > >; const selectedUsers = ['Ruth', 'Daniel']; const filteredUsers = Object.keys(users) .filter(key => selectedUsers.includes(key)) .reduce((obj, key) => < objJavascript filter для object = usersJavascript filter для object; return obj; >, <>); console.log(filteredUsers); 

In the above example, we filtered the Users object to only return objects of the selectedUsers , filtering them by the key:

Conclusion

In this short article — we’ve taken a look at filtering objects by value, using the Object.keys() method, filtered via the filter() method.

Источник

How to Filter Objects in JavaScript?

While programming in JavaScript, we often want to remove the repeated or invalid values contained in an object or delete the objects holding certain values. In such cases, filtering the objects in JavaScript can help to reduce the complexity and deleting the extra entries to make the code readable and understandable.

This blog will demonstrate the methods to filter objects in JavaScript.

How to Filter Object in JavaScript?

An object can be filtered in JavaScript by applying the “filter()” method:

Let’s check out each of the mentioned scenarios one by one!

Method 1: Filter Object in JavaScript by Applying filter() and search() Methods

The “filter()” method creates a new array of elements according to the applied condition. Whereas the “search()” method searches the specified string in an array. These methods can be used to search for a particular object value and filter it.

In the given syntax, the “function” refers to the function that needs to be executed for each array item, and the argument values of the function refer to the “index” of the current element in an array and “this” is the value passed to the function.

In the above syntax, the search() method searches for the “value” in the given string.

Example
Firstly, declare an array of objects with the “name” properties and corresponding values:

let objData = [ { name : «Rock» , id : «1» , alive : true } ,
{ name : «John» , id : «2» , alive : true } ,
{ name : «David» , id : «3» , alive : false } ]

After that, apply the filter() method on the value of the “alive” property in such a way that the object having the specified property’s boolean value as “false” will be filtered out from the array:

Next, the “filter()” method will be applied having the value “item” as its argument which will be passed to the accessed objects array in such a way that the “search()” method will search for the specific object value “Harry” and filter it out using the former method:

Finally, the filtered objects will be displayed on the console:

The corresponding output will be as follows:

It can be seen that the specified value is filtered out from the given array of objects.

Method 2: Filter Object in JavaScript by Applying filter() Method Based on the Object’s Boolean Values

The “filter()” method can similarly be utilized in this method to filter the objects by accessing their specific properties and filtering them based on the corresponding boolean values of the added properties.

Example
In the following example, we will similarly declare an array of objects holding a string, numeric, and boolean type properties and their corresponding values:

let objData = [ { name : «Rock» , id : «1» , alive : true } ,
{ name : «John» , id : «2» , alive : true } ,
{ name : «David» , id : «3» , alive : false } ]

After that, apply the filter() method on the value of the “alive” property in such a way that the object having the specified property’s boolean value as “false” will be filtered out from the array:

As a result, the filtered objects having the boolean value “true” will be logged on the console:

Method 3: Filter Object in JavaScript by Applying filter() Method Based on Condition

In this particular method, we will utilize the “filter()” method to filter out a particular object property based on the added condition in its argument.

Look at the following example for demonstration.

Example
First, declare an array of objects as follows:

let objData = [ { name : «Rock» , id : «1» , alive : true } ,
{ name : «John» , id : «2» , alive : false } ,
{ name : «David» , id : «3» , alive : false } ]

Next, apply the “filter()” method on the “id” property of the objData in such a way that objects having id less than three will be stored in the “filterObj” and the remaining will get obsolete:

Last, log the filtered objects satisfying the above condition on the console:

In the given output, it can be observed that the objects are filtered out based on the value of “id” irrespective of the assigned boolean values.

We have discussed various methods to filter objects in JavaScript.

Conclusion

To filter objects in JavaScript, apply the “filter()” and “search()” methods in combination to search for the object’s value and filter it. Moreover, only the filter() can be utilized to filter out the property of an object based on the added conditions. This write-up has explained three methods to filter objects in JavaScript.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.

Источник

Оцените статью