What is the best method for retrieving key-value pairs from an object based on a specific string filter?

const obj = {
"pi_diagram": null,
"painting": null,
"heat_treatment": null,
"welding_procedure": null,
"inspection_test": null,
"pipecl_hadoop": null,
"pipecl": null,
"ludo_min_hadoop": null,
"ludo_min": 4,
"ludo_normal_hadoop": null,
"ludo_normal": 6,
"ludo_max_hadoop": null,
"ludo_max": null,
"ludo_test": null,
"ludo_mech_min": null,
"ludo_mech_max": null,
"ludo_unit": "barg",
"temp_min_hadoop": null

}

I have the above object and I need to extract key value pairs with '_hadoop' in the key name. Can anyone help me with this?

Answer №1

Here is a helpful reference for you: JavaScript: filter() for Objects

Based on your question, the solution could be implemented as follows:

   const obj = {
      "pi_diagram": null,
      "painting": null,
      "heat_treatment": null,
      "welding_procedure": null,
      "inspection_test": null,
      "pipecl_hadoop": null,
      "pipecl": null,
      "ludo_min_hadoop": null,
      "ludo_min": 4,
      "ludo_normal_hadoop": null,
      "ludo_normal": 6,
      "ludo_max_hadoop": null,
      "ludo_max": null,
      "ludo_test": null,
      "ludo_mech_min": null,
      "ludo_mech_max": null,
      "ludo_unit": "barg",
      "temp_min_hadoop": null
    };
    const filteredByKey = Object.fromEntries(Object.entries(obj).filter(([key, value]) => key.includes('_hadoop')))

console.log(filteredByKey);

Answer №2

const dataObj = {
  "pi_diagram": null,
  "painting": null,
  "heat_treatment": null,
  "welding_procedure": null,
  "inspection_test": null,
  "pipecl_hadoop": null,
  "pipecl": null,
  "ludo_min_hadoop": null,
  "ludo_min": 4,
  "ludo_normal_hadoop": null,
  "ludo_normal": 6,
  "ludo_max_hadoop": null,
  "ludo_max": null,
  "ludo_test": null,
  "ludo_mech_min": null,
  "ludo_mech_max": null,
  "ludo_unit": "barg",
  "temp_min_hadoop": null
}

let resultMap = {}
for (const [key, value] of Object.entries(dataObj)) {
  if (key.includes('_hadoop')) {
    resultMap[key] = value
  }
}
console.log(resultMap)

Answer №3

To ensure that a name must end with "_hadoop" and does not contain "_hadoop", you can utilize a regular expression (regex) like `/hadoop$/.test(propName)`.

Obtain an array of all keys from the object using `Object.keys(obj)`, then filter it with `/hadoop$/.test(x)` to get an array of keys that end with "_hadoop".

Subsequently, employ `reduce` function to construct your new object.

View the outcome below.

const obj = {
  "pi_hadoop_diagram": null,
  "painting": null,
  "heat_treatment": null,
  "welding_procedure": null,
  "inspection_test": null,
  "pipecl_hadoop": null,
  "pipecl": null,
  "ludo_min_hadoop": null,
  "ludo_min": 4,
  "ludo_normal_hadoop": null,
  "ludo_normal": 6,
  "ludo_max_hadoop": null,
  "ludo_max": null,
  "ludo_test": null,
  "ludo_mech_min": null,
  "ludo_mech_max": null,
  "ludo_unit": "barg",
  "temp_min_hadoop": null
};

let result = Object.keys(obj)
  .filter(x => /_hadoop$/.test(x))
  .reduce((a, x) => (a[x] = obj[x], a), {});

console.log(result);

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

Sinon threw an assertion error out of the blue

Just diving into using Sinon and facing a small hiccup. Let's say we have a module (named myModule.js) defined as follows: //myModule.js var _f2 = function() { console.log('_f2 enter'); return {prop1:'var1'}; }; var f1 = ...

"Disabling Dropzone.js functionality once a file has been selected - here's how

When using my dropzone, I typically choose a file to save first and then click the save button. However, I am facing an issue: how can I disable the dropzone area after selecting a file? I attempted the following approach: accept: function (file, done) { ...

Is it possible to implement a setInterval on the socket.io function within the componentDidMount or componentDidUpdate methods

I'm currently working on a website where I display the number of online users. However, I've encountered an issue with the online user counter not refreshing automatically. When I open the site in a new tab, the counter increases in the new tab b ...

What could be causing my PrimeReact dropdown component to ignore the custom class styles?

Within my Project, I am utilizing multiple Prime React dropdown components and I am aiming to customize one of them with a unique style. In my CSS, I have established global styles to overwrite the default settings for all the dropdowns. However, when tryi ...

Utilize D3's pie chart to showcase the data in JSON's individual collections

I am currently working on creating a pie chart that displays the distribution of collections based on their names. I have come across an issue where d3.layout.pie().value() only evaluates specified array values. Is there a solution available to extract the ...

Utilizing Next.js named imports without server-side rendering

I am looking to update this code snippet to use next.js dynamic imports without server-side rendering (SSR) import { widget } from "./charting_library/charting_library"; Here is what I have tried so far const widget = dynamic(() => import(&qu ...

Using the class method to handle jQuery events alters the context

Is it possible to access the class context from within a method being used as a jQuery event handler? The example below illustrates the scenario: class EventHandler { constructor() { this.msg = 'I am the event handler'; } ...

How can you receive a file through AJAX response?

I have a standard Ajax function that I regularly use to call a specific function within my node.js server. This particular function is responsible for retrieving a file (usually in xls format) from the server and streaming it back to the client. Below is ...

Learning how to use Express.js to post and showcase comments in an HTML page with the help of Sqlite and Mustache templates

I am facing a persistent issue while trying to post new comments to the HTML in my forum app. Despite receiving various suggestions, I have been struggling to find a solution for quite some time now. Within the comments table, each comment includes attrib ...

JavaScript can be used to append multiple array values within double brackets in Spring MVC

I am currently developing an application using Spring MVC with MongoDB. In the collection, I have retrieved multiple image name values: Ex: 1.jpg, 2.jpg, 3.jpg.... My Query: Now I need to place these values inside double brackets [[]] Ex : [["1.jpg"," ...

Bootstrap.js has the ability to utilize nested objects for organizing and

As I work on enhancing a Combobox class I developed to complement Bootstrap 4, I am aiming to align the Javascript with the existing Bootstrap code. During this process, I came across a snippet of code in bootstrap.js while studying the Modal component: ...

What is the process for including the posting date in the JSON format while using the Instagram

Struggling to incorporate the date into my JSON Instagram feed has been a challenge for me. For reference, here is a demonstration on JSFiddle: http://jsfiddle.net/galnova/p74jy3sk/ The following code snippet includes the commented-out section related to ...

What is the reason for webpack adding "-es5" and "es2015" to my TypeScript files?

When Webpack converts my typescript files into Javascript files, it appends -es5 to the name. For instance, I expect the file to be named background.js, but it actually generates 4 separate files: background-es5.js background-es5.js.map background-es2015. ...

How to Utilize Raw HTML in GWT with the Power of Jquery/Javascript?

Below is the HTML code snippet: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function( ...

Alternative to Webpack for modifying global variables in preloaded modules

Is there a way to shim moment.js in webpack similar to how it is done in browserify? I have developed a widget using npm and webpack, which will be included in another application. The other app already has moment.js loaded via a script tag. I want to av ...

Trouble with toggling div visibility using jQuery and AJAX

I'm trying to display a specific div based on the result of an SQL query. The problem I'm facing is that I can't seem to toggle the divs asynchronously. Currently, the page needs to be reloaded for the div to reflect the changes. <?ph ...

Enhancing link functionality with jQuery on a dynamically generated server page

I am facing an issue with my navigation menu that includes dropdowns. On desktop, the parent items need to be clickable as well, which is not a problem. However, for it to be responsive on mobile devices, I need to account for the lack of hover capability. ...

Retrieve the current date in the format of dd/mm/yyyy using AJAX request

var currentDate = new Date(); var todayDate = currentDate.getDate() + '/' + monthNames[currentDate.getMonth()] + '/' + currentDate.getFullYear(); This is my current date retrieval method. It works well but has a minor issue. For to ...

Issue: The `libsass` component could not be located

When attempting to run an Express app using node-sass-middleware on Ubuntu, I encountered this error: 0 info it worked if it ends with ok 1 verbose cli [ '/home/mohamed/.nvm/versions/node/v0.12.7/bin/node', 1 verbose cli '/home/mohamed/.n ...

Converting Repository Objects to Json in Symfony3

element, I am facing an issue while attempting to send a repository object as JSON. In my controller code, I have implemented a conditional check to ensure that the request is made via XmlHttpRequest. Upon receiving the data and fetching the corresponding ...