Retrieve the value of a key by using the value of a different key within an object

I often encounter a situation where I need to extract just an object key, rather than the entire object, based on another key value in the same object from an array of objects.

For instance, consider the following array of objects:

myArray = [
  {
    name: Person 1
    type: alpha
  },
  {
    name: Person 2
    type: beta
  },
  {
    name: Person 3
    type: gamma
  },
  {
    name: Person 4
    type: beta
  },
  {
    name: Person 5
    type: gamma
  },
];

If I want to retrieve only the name values for objects with a type of 'beta', how can I accomplish that? I am partial to lodash and familiar with using _.map or _.filter, such as:

var newArray = _.map(myArray, function(item) {
  return item.type === 'beta';
});

However, these methods return the entire object. I believe chaining may hold the solution, but I am struggling to identify how to achieve my desired outcome.

Thank you.

Answer №1

If you want to achieve this, you can utilize the built-in Array.prototype.map() method. Here's an example using ES6 fat-arrow functions for brevity:

myArray.filter(item => item.type === 'beta').map(item => item.name)

For those who prefer the ES5 syntax, it would look like this:

myArray.filter(function(item) {return item.type === 'beta'})
     .map(function(item) {return item.name})

Answer №2

This code snippet demonstrates how to use lodash's map and filter functions together.

var result = _(myArray).filter({ type: 'beta' }).map('name').value();

var myArray = [
  {
    name: 'Person 1',
    type: 'alpha'
  },
  {
    name: 'Person 2',
    type: 'beta'
  },
  {
    name: 'Person 3',
    type: 'gamma'
  },
  {
    name: 'Person 4',
    type: 'beta'
  },
  {
    name: 'Person 5',
    type: 'gamma'
  },
];

var result = _(myArray).filter({ type: 'beta' }).map('name').value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Answer №3

If you want to extract only the names of items with type 'beta' from an array, you can achieve this by using the combination of filter and map methods:

myArray.
   filter(function(item){ return item.type === 'beta'; }).
   map(function(item){ return item.name; });

Answer №4

Utilizing ES6 parameter destructuring:

myArray.filter(({type}) => type === 'beta').map(({name}) => name)

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

Attempting to extract JavaScript URLs using scraping methods, however, receiving an empty string when utilizing

I need help accessing and extracting data from a URL that is embedded within a specific tag. The tag in question looks like this: <script src="http://includes.mpt-static.com/data/7CE5047496" type="text/javascript" charset="utf-8"></script> S ...

flexible side-by-side alignment - adaptable grids

I am currently working on a website project that involves a ul list with responsive columns. The column width adjusts based on the window size, and I aim to center-align the text within the li element according to the new column width. If you want to view ...

Issue with jQuery AutoComplete display rendering inaccurately

I have encountered an issue with two jQuery autocomplete components on my website. Despite being very similar, one functions correctly while the other does not. The functional code snippet is: @Html.TextBoxFor(model => model.Part, new { @id = "txtPart ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

The process of embedding a .js file into an HTML document involves

The question appears to be straightforward. The common approach is to simply utilize this code snippet: <script src='https://code.angularjs.org/1.0.0rc9/angular-1.0.0rc9.js' type='text/javascript'/> Alternatively, in Jsfiddle, we ...

Can a scope variable be passed from a controller to a service function in Angular?

angular.module('store_locator') .constant("baseURL","http://locator.sas.dev.atcsp.co.za/api/") .service('stationsService', ['$http', 'baseURL', function($http,baseURL) { this.getStations = ...

Tips for Implementing Show and Hide Functionality in JavaScript

I have a piece of cshtml code similar to the following: <span class="p1"> Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book authored by Rajiv Malhotra and Aravindan Neelakandan, arguing ...

Within Angular2 NGmodule, I aim to dynamically load two distinct sets of route modules depending on certain conditions

In Angular2, I am looking to load two different sets of route modules - one for jobseekers and the other for employers. Both sets will have the same URLs but will contain different modules for jobseekers and employers. Therefore, I need a way to dynamicall ...

I could not retrieve data from the Promise {} object

Currently, I am in the midst of developing a discord bot using discord.js. When attempting to retrieve the target user, I utilize the following code: let target = message.guild.members.fetch(id). This method yields either Promise { <pending> } if the ...

Perl displays the error message: "Cannot utilize a string as an array reference."

I've been honing my Perl skills with a challenge from codeeval.com, but I hit a snag. The task involves reading a file line by line, where each line contains a string and a character separated by a comma, and finding the rightmost occurrence of that c ...

Transform a loaded image into canvas

I have encountered a challenge while working on a plugin where I need to convert an Image into Canvas and store it as data URL. The function currently triggers on the 'load' event, but how can I achieve this conversion for an image that is alread ...

Managing user sessions in Node.js

What is the best way to manage SESSIONS in Node.js? Specifically, I am interested in storing a UserID in a session using Node.js. How can this be accomplished, and is it possible to access that Node.js session in PHP as well? I am looking for an equivale ...

Converting PHP array into a JavaScript object array

I have a database table with three columns labeled as prop_no, prop_name, and prop_sc. The data from the last two columns has been extracted into two distinct PHP arrays named $propertyNameList and $propertyCodeList. I am now facing the task of transferrin ...

Utilizing $index in AngularJS while iterating through ng-repeat items

Here is an example of an unordered list: <ul class="dropdown-menu inner" role="menu"> <li ng-repeat="availableAlphaName in availableAlphaNames" data-original-index="0" data-optgroup="1" class=""> <a tabindex="0" class="opt " st ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

Securing your Node.js connect-rest REST API with OAuth: A comprehensive guide

After conducting an extensive search on Google for examples related to my query, I was left empty-handed due to the generic name of the "connect-rest" package. My objective is to secure a server side API that I have built using the Node module "connect-re ...

Sending users to either Page A or Page B depending on the response received from the API

Currently facing a dilemma. Imagine having a main hub page where you can navigate to either page A or page B. On this main page, there is a list of items. The goal is to trigger a GET API call upon clicking any item in the list. Based on a boolean field i ...

What is the best way to give a fixed height to Card content in Material UI? Is CSS the way to go?

I've been struggling with a design issue involving Material-UI cards used to display News. The problem arises when the paragraph section of the card occupies multiple lines of text. When it spans two lines, there is a 10px spacing between the paragrap ...

Why You Can Only Use elementByCssSelector Once on TheIntern.io/Selenium

I'm encountering a peculiar problem while running a functional test with Selenium (using the Intern.io framework) where only the first element is being recognized; any subsequent element I try to access throws an error: Error: Error response status: ...

What is the method for adjusting the amount of rows shown in ng-grid?

As I leverage ng-grid for data presentation, I notice that approximately 10 rows are visible before the vertical scrollbar appears and conceals the remaining data. Is there a way to adjust the threshold for when the vertical scrollbar kicks in? ...