Ways to retrieve both keys and values from an array efficiently using array functions

Given the following array:

const school = [
  { Students: 4, Teachers: 15, Department: 'Mathematics' },
  { Students: 4, Teachers: 15, Department: 'English' },
  { Students: 4, Teachers: 15, Department: 'Science'} 
] 

I am interested in retrieving all values associated with a specific key:

const students = [
  { Students: 4 },
  { Students: 4 },
  { Students: 4 }
] 

Instead of using a for in loop, is there a way to achieve this utilizing methods like map, filter, find, or reduce? I have been struggling to extract the key value.

Solution:

school.map(data => `Students: ${data.Students}`);

You can encapsulate this functionality within a function:

getByKey(arr, val) {
    arr.map(data => `${val}: ${data[val]}`);
}


getKey(school, Department)

Answer №1

To simplify the process, focus on extracting information related to Students only by utilizing map method.

const university = [{
  Students: 46,
  Lecturers: 2,
  Faculty: 'Mathematics'
}, {
  Students: 65,
  Lecturers: 6,
  Faculty: 'English'
}, {
  Students: 48,
  Lecturers: 4,
  Faculty: 'Science'
}]

let result = [];

result = university.map(obj => {
  return {
    Students: obj.Students
  }
});

console.log(result)

Answer №2

To extract specific keys from an array of objects, you can utilize the map function along with fromEntries to create a new object containing only the desired keys.

const data = 
  [ { Name: 'Alice', Age: 25, Country: 'USA' }, { Name: 'Bob', Age: 30, Country: 'Canada'} , { Name: 'Eve', Age: 22, Country: 'UK' } ];
  
const selectKeys=(arr,keys)=> arr.map(obj=>Object.fromEntries(keys.map(key=>[key,obj[key]])));

console.log(selectKeys(data, ['Name', 'Country']));
console.log(selectKeys(data, ['Age']));

Answer №3

A neat and efficient way to achieve this is by utilizing the map() function:

const classes = school.map(function(s){
    return {"Classes" : s.Classes};
});

Answer №4

Employing the map function, all without utilizing the return keyword:

college.map(college=>({Graduates:college.Graduates}));

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

Display the child elements in an HTML document that have the same class name as the parent element, while concealing all

<div class="element-2"> <div class="element-1"> <p>div 1</p> </div> <div class="element-2"> <p>div 2</p> </div> </div> The main objective is to display only child divs with sim ...

Tips for developing integration tests for medium-sized nodejs applications with heavy reliance on 3rd party APIs

I am the owner of a medium-sized nodejs application that can be found on GitHub under the link here. This application heavily relies on various 3rd party APIs to function. Essentially, the purpose of this app is to make calls to different Salesforce APIs, ...

Differences between addEventListener and jQuery's on method, as well as form.submit and jQuery's

I encountered a situation where callbacks registered using jQuery's on method were not being called when trying to trigger form submission with the HTML Form element object instead of jQuery. After some testing, I discovered that changing the code to ...

Customize time formatting in Angular to accommodate localized time formats

I am utilizing Angular's localization service version 8.3.28 to support English, Spanish (Mexico) with code es-MX, and Spanish (Spain) with code es-SP While using the date pipe: {{ foo.Date | date: 'shortDate' }} The dates are changing to ...

Having Trouble with Bootstrap 4 JQuery Responsive Tabs? Check out the provided code snippet for a solution

So I have included a code snippet to showcase the issue. In my current code, I am using a jinga forloop to generate the cards. Each card contains responsive tabs. However, when you click on the tabs of card 2 to view its data, it ends up displaying the d ...

Saving multiple instances of an object using Mongoose

In my Mongoose model, I have a blog schema where each blog can have multiple comments attached to it. var mongoose = require('mongoose') , Schema = mongoose.Schema var blogScheam = Schema({ title: String, comments: ...

Table expands to full width

I am facing an issue with a table that has a large number of elements. I would like the table to expand to the full width of the screen, but it slows down significantly when it does so. https://i.sstatic.net/s475I.png However, I have noticed that if I se ...

use ajax to post saved data to a WebAPI in php

I have successfully implemented the code to save data in a custom table using Ajax. Now, I need to figure out how to send this data to an asp.Net API using js/jQuery. How can I achieve this? Below is my HTML form and JS code: <div id="inline1" class= ...

Learn how to utilize Javascript to easily drag and drop an image within the same block

I am encountering an issue with dragging and dropping images or swapping them using JavaScript. I have tried to implement this in the code below, where clicking on icons moves them onto a colored div. However, I am now trying to drag and drop the images wi ...

Custom options titled MUI Palette - The property 'primary' is not found in the 'TypeBackground' type

I am currently working on expanding the MUI palette to include my own custom properties. Here is the code I have been using: declare module '@mui/material/styles' { interface Palette { border: Palette['primary'] background: Pa ...

Refreshing the state when making changes to ng-repeat through orderBy and/or filter

I'm new to Angular JS and while I understand JavaScript in general, Angular has a different approach that is challenging for me. Specifically, I am struggling with sorting an array of objects by a property and filtering them based on a string provided ...

A guide on extracting the value of a key from an object in angularjs

I stored the data in an object like this: $scope.modelName = { name: {} }; The data was saved as {"APPLE":true,"ORANGE":true}. I am attempting to retrieve only the keys and save them in another object using a for loop. However, I'm having troubl ...

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

Having Trouble with Jquery UI Date Picker?

I have included my form code below. <div class="threeleft second" id='displayallformshow' style="float: none;width: 80%;padding:10px;"> <form action="investor_submit.php"> <div class='formdiv'> ...

Creating a single submit handler for multiple forms in React

I am using a shared event handler for form submissions. handleSubmit = (e) => { e.preventDefault(); const errors = this.validate(); this.setState({ errors: errors || {} }); if (errors) return; this.doSubmit(); }; This event handle ...

The functionality to remove table rows when checkboxes are selected is not functioning as expected in an Angular 7 application

My table contains data generated from a loop. When I click the edit button, additional buttons and textboxes are enabled. If multiple checkboxes are checked, the add buttons become disabled. However, if all checkboxes except one are unchecked, the add bu ...

Receiving a null result when parsing a JSON file from a URL in JavaScript

My data loading query loads JSON data without any issues, as shown in this snippet: $(document).ready(function () { var json = [{"id":1,"first_name":"Debra","last_name":"Rodriguez","email":"[email protected]","gender":"Female","ip_address":"90. ...

fill collections within backbone

Looking to optimize populating a Backbone collection, I have come across the push method but it requires iterating over all items: define([ ... ], function($, _, Backbone, imagesCollection, imageTemplate, gridView) { var AppView = Backbone.View.ex ...

Angular Ordering Map Object

Having an issue that I need help with: I have generated a key-value list and I am looking to sort it in descending order. As you can see in the stackblitz example, I have demonstrated how I create the list and attempt to sort it using different methods. Ho ...

What is the best way to display time instead of angles in highcharts?

Hey there! I'm currently working with highcharts and I have a polar chart where I want to display time on the y-axis instead of angles. Here's what I've tried so far: On the x-axis, I have angles and I've set tickInterval: 45,. How can ...