Filtering a JavaScript map object by an array of specific keys

I am faced with the task of filtering a JavaScript map object based on an array of keys:

var arr = ['var1', 'var2', 'var3']

The Javascript map consists of four key-value pairs (var1: 1, var2: 2, var3: 3, var4: 4) and I need to extract only the items that match the keys in the arr array. Can someone assist me in achieving this filter operation?

Answer №1

To create a new object using the reduce method in JavaScript, you can follow this example:

const originalObject = {apple: 1, banana: 2, cherry: 3};
const keysToExtract = ["banana", "cherry", "date"];

const extractedObject = keysToExtract.reduce(function(result, key) {
    if (originalObject.hasOwnProperty(key)) result[key] = originalObject[key];
    return result;
}, {}); // {banana: 2, cherry: 3}

Answer №2

In order to remove a property from an object, you must utilize the delete operator.

var fruits = ['apple', 'banana', 'orange']
var animals = { lion:1, monkey:2, tiger:3, elephant:4};
var newAnimals = Object.assign({}, animals);
Object.keys(newAnimals).forEach(function(key){
   if(!fruits.includes(key))
    delete newAnimals[key];
});
console.log(newAnimals);

Answer №3

If my memory serves me right, the situation at hand is as follows :

const keysToRetain = ["var1", "var2", "var3"];
const objectData = {
  "var1": 1,
  "var2": 2,
  "var3": 3
};

If this assumption holds true, then you can implement the following approach :

const filteredResult = Object.entries(objectData)
.filter(item => keysToRetain.includes(item[0]))
.reduce((accumulator, entry)=>{
  accumulator[entry[0]] = entry[1];
  return accumulator;
}, {});

Alternatively,

const filteredResult = Object.entries(objectData)
.map(item => ({
  "key": item[0],
  "value": item[1]
})).filter(item => keysToRetain.includes(item.key))
.reduce((accumulator, entry)=>{
  accumulator[entry.key] = entry.value;
  return accumulator;
}, {});

This method essentially filters out entries in the object based on whether their key matches any of the specified keys, and then compacts them back into an object.

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

Android Memory Issue, EMA Alert: "byte[]" loaded via "<system class loader>"

I am currently developing a small Android app with just a single activity, and I have encountered a memory leak issue that I am struggling to identify. The app performs basic calculations and presents the results in a structured format. While the calculati ...

Implementing jQuery to trigger actions on every other click

Here we have a snippet of code that either posts and updates #arrival or removes it and replaces it with standard text. One click for posting, another click to reset. The issue is that currently it requires two clicks to do the initial posting, followed by ...

Learn how to efficiently send multiple image files to the server by utilizing Formidable and React JS

I am encountering an issue while attempting to upload five images to the server. The code file is provided below, and any assistance would be greatly appreciated. In this scenario, I am inputting image files and storing them in an array, but Formidable in ...

To ensure that the first three digits of a phone number are not zeros, you can implement a JavaScript function to validate the input

I've been working on validating a phone number using JavaScript, but I've hit a roadblock. I need to ensure that the area code (first 3 numbers in 999) cannot be all zeros (0). While I know how to create the desired format (like xxx-xxx-xxxx), ...

Latest FF 35 showing alert for blank field in HTML5 email input box

My form includes an email input field with a default value. When the user focuses on the field, it clears out if the value matches the default one. Upon blurring the element, the default value is restored if the field remains empty. In Firefox 35, clickin ...

Transforming a "singular or multiple" array into an array of arrays using TypeScript

What is causing the compilation error in the following code snippet, and how can it be resolved: function f(x: string[] | string[][]): string[][] { return Array.isArray(x[0]) ? x : [x]; } Upon inspection, it appears that the return value will constantly ...

What is the best way to include an ajax request within a function and execute it only when needed?

I am working on an ajax request that fetches data from a specific URL. I have the following code snippet: $.ajax({ type: 'POST', url: '/get-result.php', dataType: 'json', data: 'pid=' + $(this).attr( ...

Secrets to concealing a Material UI column based on specific conditions?

Recently, I encountered a challenge with my MUI datagrid where I needed to hide a column based on a specific role. Below is the code snippet: const hideColumn = () => { const globalAdmin = auth.verifyRole(Roles.Admin); if(!globalAdmin){ ...

Is it possible to eradicate arrow functions in Angular CLI?

I am facing a challenge in running my code on IE11 due to issues with arrow functions. I need to find a way to eliminate them from the build and replace them with function() {}. Even though I have removed them from main.js, they are still present in the v ...

Making sure javascript functions properly after loading content through Ajax in Wordpress

I'm currently facing an issue with loading content through Ajax. I'm encountering difficulties in getting the Woocommerce javascript to function properly when I am loading a product via Ajax. The content is being loaded in the following manner: ...

Create a CSS dropdown menu design similar to the one shown in the image

I am seeking guidance on how to replicate the design depicted in this image: https://i.sstatic.net/Hl8HZ.jpg Currently, my menu structure is as follows: body { background: white; margin: 0; padding: 0; } /* / nav */ nav { width: 100%; backgr ...

IsContainer and IsModel properties in Dragular are not functioning properly with the accept or canBeAccepted methods

Scenario 1 : Let's consider using two containers, named A (Drag Source) and B (Drop Source). Code snippet : dragularService(containerLeft, { containersModel: [DragularconTainer], copy: true, canBeAccepted: function(el, source) { ...

Why does my node-js API's second endpoint not function properly?

Currently working on my first API project. Everything was going smoothly, until I encountered an issue with my second route, app.route('characters/:characterId'). For some reason, none of the endpoints are functioning, while the first route, app. ...

Django will not be replacing the outdated image

My Django App is designed to display images on the browser based on user selections in the UI. Whenever there is a change in the UI, a JavaScript function is triggered that makes a call to a Django view. Each time I modify the UI in the browser, a new ima ...

Chrome runs requestAnimFrame at a smooth 60 frames per second, while Firefox struggles to keep up at

I recently developed a canvas animation using requestAnimFrame and saw great results in Chrome. However, when I viewed it in Firefox, it seemed like a slideshow was running instead of a smooth animation. I'm unsure what could be causing this issue. F ...

Issue with the final transition of the last image in the Bootstrap carousel

I'm currently in the process of creating my own portfolio website. I've integrated a Carousel feature inspired by Bootstrap's example. However, I've noticed some glitches in the transitions between the first or second slides and the thi ...

Ways to run a function with a delay

I'm looking to run a function at a later time, so I have written the following code: setTimeout(function(){ console.log("hi");}, 3000)); However, my issue is that I only want the message to be printed after the 3000 ms have elapsed. Can anyone as ...

Using JavaScript to search for a specific string within a row and removing that row if the string is detected

I need help with a script that removes table rows containing the keyword STRING in a cell. However, my current script is deleting every other row when the keyword is found. I suspect this has to do with the way the rows are renumbered after deletion. How c ...

JavaScript Filtering Techniques

Looking for a simpler way to remove an item from a list of 10 items without using arrow functions. My current method is shown below, but I'm seeking a more efficient solution. function getFilteredItems(myItems) { var items = ['item1& ...

Determining if a swf file has loaded using JavaScript and swfobject

Here is the code snippet I am working with: <head> # load js <script> function graph() { swfobject.embedSWF( "open-flash-chart.swf", "chart", "400", "180", "9.0.0", "expressInstall.swf", {"data-file":"{% url moni ...