Retrieve values from an array of objects using their corresponding keys

I have an array populated with various objects containing different key-value pairs. I need to extract specific values from the array and determine if a certain value is present or not.

function groupByName (contract) {
 const { age } = contract;

 const groups = [
  {name: 'John', age: 30},
  {name: 'Jack', age: 33},
  {name: 'Tom', age: 40}
  ...
 ];
 ...
}

Currently, in order to compare the age in the groups array, I rely on loop functions to iterate through each object one by one.

groups.forEach(g => {
 if (g.age === age) {
  ...
 } else {
  ...
 }
});

However, I find this method cumbersome and am seeking a simpler and more efficient solution. Any suggestions would be greatly appreciated!

Answer №1

Utilizing the filter method allows you to split a list into two separate sublists.

Here is an example:

const people = [
  {name: 'Alice', age: 25},
  {name: 'Bob', age: 30},
  {name: 'Charlie', age: 35}
]

const above30 = age => people.filter(p => p.age >= age)
const below30 = age => people.filter(p => p.age < age)

const over30 = above30(30)

const under30 = below30(30)

over30.forEach(p => {
  console.log('Dealing with people aged 30 and above:', p)
})

under30.forEach(p => {
  console.log('Handling people below the age of 30:', p)
})

Answer №2

Perhaps you might find this function helpful

groups.some(person => person.age === age)//returns true if an object meets the criteria, otherwise false

Alternatively, check out this resource about Array.some on MDN

On a side note, if you need to run an if/else statement in every iteration, consider using forEach instead

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of linear mode seems to be malfunctioning when using separate components in the mat-horizontal-stepper

In an effort to break down the components of each step in mat-horizontal-stepper, I have included the following HTML code. <mat-horizontal-stepper [linear]="true" #stepper> <mat-step [stepControl]="selectAdvType"> <ng-template matStep ...

Unlocking two features with just a single tap

I am currently working on a website for a kiosk, where the site transitions like a photoslide between each section. To achieve this effect, I have added a layover/mask on the initial page. The layover/mask is removed using a mouse click function. This is ...

My attempt to use the Redux method for displaying data in my testing environment has not yielded

I've been attempting to showcase the data in a Redux-friendly manner. When the advanced sports search button is clicked, a drawer opens up that should display historical data when the search attributes are selected. For this purpose, I implemented the ...

Stop materializecss dropdown from closing when clicking within it

As I work on my current project, I am utilizing Materialize.css which includes a dropdown with various input forms inside. The dropdown can be closed by: clicking outside of .dropdown-content clicking inside of .dropdown-content clicking on .dropdown-bu ...

finding the index of a particular checkbox in a list

I am working with a list of checkboxes that are dynamically created using JavaScript, each contained within its own separate div element. I need to determine the position number of a specific checkbox within all checkboxes sharing the same class within a p ...

Utilizing Node.js to Retrieve Data from MySQL

Hi there, I'm new to NodeJS and I'm curious about how to fetch a MySQL query like we do in PHP. $query = mysql_query("SELECT * FROM accounts"); while($fetch = mysql_fetch_array($query)) { echo $fetch['Username']; } How would this be ...

Utilizing Javascript to initiate an AJAX call to the server

I am creating an application similar to JSbin / JS fiddle. My goal is to update my database by making an ajax request to the server when the user clicks on the save code button and submits the values entered in the textarea. However, I seem to be encount ...

Is there a way to have a span update its color upon clicking a link?

I have 4 Spans and I'm looking to create an interactive feature where clicking a link in a span changes the color of that span. Additionally, when another link in a different span is clicked, the color of that span changes while reverting the previous ...

What is the best way to manage a brief webhook timeout in a Node.js environment?

The eSignatures API has been successfully integrated into our app, ensuring smooth functionality up to this point. However, an issue has arisen with the webhook function. When a client signs a document, it triggers our webhook cloud function to update our ...

Is there a way to display this JSON data using mustache.js without needing to iterate through a

Here is the JSON data: var details = [ { "event": { "name": "txt1", "date": "2011-01-02", "location": "Guangzhou Tianhe Mall" } ...

Vue component input form not providing expected result

Here is the code snippet for my "ecedata" component with an input field: <template> <div class="col-l-4"> <p style="text-align: center">Data/day (GB)</p> <div class="form-input-set" style="background: white"& ...

Is there a way to incorporate a custom method into a JQuery tab widget?

Need assistance with extending the functionality of the jQuery UI tabs widget by implementing a new method for all instances. Attempted using both $.extend() and jQuery.widget(), but encountered an issue where the newly added method remains undefined when ...

Position does not exist

I'm currently working on developing an application form that can be submitted by applicants based on the position they are interested in. However, I am facing an issue when trying to click submit on the application form, resulting in the error display ...

Node version 6.11.0 experiencing JavaScript heap error even with zero memory usage in the program

Encountering an out of memory error even though only two variables (i & j) are being used. Can someone please provide clarification? I am not storing anything in memory or saving it to any storage; whatever is generated is outputted to the console and the ...

`Why am I having difficulty transmitting HTML content with Node.js through Mailgun?`

I've been facing issues with sending HTML in my emails. To troubleshoot and prevent errors, I've opted to utilize Mailgun's email templates. Although I can successfully send out the emails, the problem arises when I receive them - the HTML ...

Creating manageable CSS styles for a wide variety of themes

I need to add themes to a web application that allows users to switch between them seamlessly. The designers want a variety of font colors and background colors, around 20 in total. Is there a way to achieve this without creating multiple .css files, which ...

Adjusting the size of the iframe to match the dimensions of the window

Is there a way to make the iframe automatically fill up the entire space? For example, only opens the iframe up to half of the window in Mozilla Firefox and IE6. How can I ensure that it takes the maximum size of the screen? Are there any CSS or JavaScr ...

What is the process for changing to a different page in NativeScript?

Having trouble creating a simple button in NativeScript labeled 'login'? I've created a login component, but when testing the code, it shows an error stating "no known component for element Login." <template> <Page> <TabV ...

Exploring Node and Express Request Query

I'm struggling with a specific endpoint setup in my code. // GET /api/logs/ app.get('/api/logs', function (req, res) { if (req.query.reverse === true) { res.send((mainModule.logs).reverse()); } else { res.send(mainModule.logs) ...

Discord bot struggling to reach every user in the server

After creating a discord bot with Discord.js, I was able to retrieve all the users from my server. However, lately I noticed that it is only returning 59 members out of the 300+ in total. I want to ensure that I am able to access all the users as before. ...