Retrieve keys from objects by specifying partial key strings using Lodash

Can LoDash's _.filter be utilized in a scenario where you want to retrieve values based on the presence of a specific string within the keys? For instance, consider the following data:

Mydata{
"banana" : "1"
}

If I aim to extract values containing "ana", how can this be achieved using LoDash? While most resources focus on searching element values, I am interested in filtering based on keys.

Answer №1

If you are looking to retrieve an array of values where the keys meet a specific condition, Lodash's _.filter() can be used with objects as well. The second parameter passed to the callback function is the key.

var data = {
  "banana": 1,
  'lorem': 2,
  '123ana': 3
}

var result = _.filter(data, function(v, k) {
  return _.includes(k, 'ana');
});

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

If you need an object where the properties adhere to a specific criterion, you can opt for _.pickBy() in a similar manner.

var data = {
  "banana": 1,
  'lorem': 2,
  '123ana': 3
}

var result = _.pickBy(data, function(v, k) {
  return _.includes(k, 'ana');
});

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

Answer №2

To achieve the desired outcome, you can utilize the built-in Array#reduce method to filter and return an object with keys that contain a specific string.

const data = {
  apple: 'red',
  banana: 'yellow',
  strawberry: 'red',
  peach: 'orange',
}

const filterByKey = (dataObject, keyword) => {
  return Object.keys(dataObject).reduce((result, key) => {
    if (key.includes(keyword)) {
      result[key] = dataObject[key];
    }
    return result;
  }, {});
}

console.log(filterByKey(data, 'app'));

Answer №3

To retrieve keys containing a specific substring, you can start by utilizing the filter() method, followed by using the map() method to extract values.

var data = {
  "banana": 1,
  'lorem': 2,
  '123ana': 3
}

var result = _.chain(data)
  .keys()
  .filter(e => _.includes(e, 'ana'))
  .map(e => data[e])
  .value()
  
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

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 or conceal a div based on the size of the screen using HTML and CSS

Hey there, I recently finished my first React Project and I’m wondering if there’s a way to hide the 'side-menu' section on mobile screens using CSS. Any suggestions? <div className='side-menu'> <SiderComponent /> < ...

Utilizing Python for Handling JSON Files

I am currently attempting to download a JSON file, store the file locally, and then loop through the JSON data to extract and save all relevant information into variables. My ultimate goal is to format this data into a CSV message for transmission to anoth ...

Form submission requires a checkbox to be checked

I have been searching for a way to make checkboxes required. Is there a method similar to using required="required"? Currently, I generate my checkboxes in the following manner and would really appreciate any guidance on this topic. It's crucial for m ...

Employ a class function within router.get

I'm a beginner with node.js and I'm running into an issue when trying to use a class method in the router.get callback function. Can someone assist me with this problem? Route.get() is expecting a callback function but received a [object object] ...

Tips for implementing an if else statement in ReactJS while utilizing the useEffect hook

Below is the code snippet for returning a Plotly graph. I would like to display a message or alternative layout when there is no data available for the graph, such as showing "No data available". How can I achieve this? import React, { useEffect } from ...

Using AngularJS: Implementing asynchronous $http.jsonp request through a service

I am currently developing a straightforward application that involves the following steps: 1. The user provides 2 parameters and clicks a button 2. Angular communicates with an external JAVA Servlet that sends back JSON data 3. The application displays the ...

What is the best way to create a nullable object field in typescript?

Below is a function that is currently working fine: export const optionsFunc: Function = (token: string) => { const options = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, } ...

Stop images from being stored in the database instead of text characters

Using a proxy, I attempt to parse some HTML. One of the elements is retrieved using jQuery: var site = 'http://www.kartabu.com/pl/index.php?filter=random' var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeUR ...

Nodejs registration and user verification process for accessing account features

I am facing a decision on how to handle two types of users - vendors and buyers. Should I develop separate APIs for registering and authenticating each user type, or should I create a single API to manage both? When designing my database model, should I h ...

include a new value to the current state array within a react component

I am working with an array in React State and I need to add a new property called Value. However, every time I try to add it, it creates a new item in the array. What I actually want is for the new property to be added as follows: value: '' Belo ...

Understanding ElasticSearch Output Detailed Explanation: Delving into Nested Description Levels with Weight or CustomScore Values

Currently, I am analyzing the Elasticsearch explain output in order to determine the maximum depth of the first relevant description within the value, description, details combination. Specifically, I am interested in parsing descriptions that contain eith ...

What steps should I take to resolve the "Module Not Found" issue that occurs when I use the command "npm start" after setting up a new React project with npm?

Just starting out with React.js and npm and encountered an issue. After using the command: npm create react-app my-test-npm-react-app I waited for the project to be created successfully. However, when I tried running: npm start I received the followin ...

How can one view all the static variables and methods associated with a class in Typescript or ES6?

Is it possible to retrieve all static variable names and static method names associated with a class, similar to how the Object.keys method returns a list of key names attached to an object? Typescript Example: class FindStatics { static num1:string = ...

How to detect the Back Button or Forward Button events in a single-page application

Currently, I am developing a single-page application that utilizes ASP.NET MVC, Backbone.js, and JQuery. My task involves capturing the browser's back and forward button events for breadcrumb implementation. I previously attempted to use the hashchan ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

The incorrect z-index value for a triangle in Three JS is causing a visual distortion

I recently ran into an issue while working with Three.js that I need help with. Here is the problem I encountered: After doing some research, it seems like this is a CanvasRenderer problem. Is there a way to resolve this without switching to WebGLR ...

Displaying and concealing table rows based on selected items

After spending a whole day trying to get this HTML/java script to work properly, I came across some code online that I used here. My goal is to have the "Colors*" row not displayed when the page loads, but to show the color options when a shirt size is sel ...

How can I display the most recent offcanvas opening at the top of the page?

The issue I'm facing is related to the offcanvas3 opening behind offcanvas2. It appears like this: $("#open-offcanvas2").on("click", function(){ $("#offcanvas2").offcanvas("show") }) $("#open-offcanvas1").on("click", function(){ $("#offcanvas1" ...

Error in Gnip - encountered a urllib2.URLError when attempting to create a job

I am currently facing an issue while attempting to create a job using the Gnip Historical Powertrack API. The problem seems to be related to the urllib module. import urllib2 import base64 import json UN = '' # YOUR GNIP ACCOUNT EMAIL ID ...

Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue. See my code below: let toppingsCount; const burger = document.createElement('div'); const toppingsD ...