Filtering objects in JavaScript using a technique similar to list comprehension

I'm dealing with a basic array structure that resembles:

obj = {1:false, 2:true, 3:true}

My goal is to extract an array containing all the keys in the object that have a value of true.

In Python, you can achieve this easily using:

>>> [key for key in obj if obj[key]]
[2, 3]

Is there a succinct or one-line method to accomplish this task in JavaScript? I also happen to have lodash at my disposal.

Answer №1

For those with Ecma5 compatible browsers, you have the ability to achieve this by utilizing Object.keys and Array.filter:

> Object.keys(data).filter(function(key) {return data[key]});
> ["4", "5"]

Answer №2

To achieve this using the latest JavaScript syntax, follow these steps:

const obj = {A:false, B:true, C:true};

const result = Object.keys(obj).filter(key => obj[key]);

console.log(result); 

Answer №3

If you're using Firefox version 30 or higher, you can achieve this.

obj = {1:false, 2:true, 3:true};
[for (key of Object.keys(obj)) if (obj[key]) key ]; 

This code snippet will give the following output:

["2", "3"]

As of now, Firefox is the sole browser that supports Array Comprehension.

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

I am looking for a way to display or conceal text depending on the presence of an image

Could you please help me with this? I am looking for a solution where text is displayed only when there is content in the src attribute of an img tag. Essentially, I need JavaScript code that can identify if an attribute has content and then make a paragra ...

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

What is the best way to simulate global variables that are declared in a separate file?

dataConfiguration.js var userData = { URIs: { APIURI: "C" }, EncryptedToken: "D" }; configSetup.js config.set({ basePath: '', files:['dataConfiguration.js' ], ..... UserComponentDetails: .....some i ...

There is no 'Access-Control-Allow-Origin' header found on the requested resource in Heroku for Node.js

Here is the header setup in my Node.js API app: res.header("Access-Control-Allow-Origin", "*"); res.header( "Access-Control-Allow-Headers", "Origin, X-Requested, Content-Type, Accept Authorization" ); ...

Refresh the information displayed in the open Google Maps Infowindow

Experimenting with extracting JSON data from a bus tracker website and integrating it into my own version using Google Maps. Although not as visually appealing, I'm struggling to update an infowindow while it remains open. Despite finding some example ...

The scrollIntoView function is not functioning as expected

Having an issue with my function called scrollIntoView. It just refuses to work :( Take a look at the code below: HTML <section class="page_mission"> <div class="page_mission_text"> <div class="scroll-animations"> <di ...

Retrieve isolated scope of directive from transcluded content

I am not certain if it is possible, but I am essentially looking for a reverse version of the '&' isolate scope in AngularJS. You can check out this Plunkr to see an example. In essence, I have created a custom directive that provides some r ...

Tips for utilizing 'toHaveClass' to find a partial match in Jest?

When I assign the class success to an element, React-Mui appends additional text to it in the DOM, such as mui-AbcXYZ-success. This causes my test using the code snippet below to fail: expect( getByTestId('thirdCheck')).toHaveClass("success ...

What is the best way to delete rows from an HTML table?

I am trying to update the table, but every time the setInterval function is triggered, the append method adds the same rows again. I want the old rows to be removed before inserting the new ones. $(document).ready(function() { function updateT ...

What steps are involved in creating a default toolbar for a material picker in a React application?

Looking for assistance with customizing the toolbar for material picker (v3) by adding a title inside the dialog. I successfully implemented this in the KeyboardDatePicker following a helpful thread (https://github.com/mui-org/material-ui-pickers/issues/11 ...

Lining Up Radio Buttons Horizontally Using CSS: Alignment Issues in Mozilla and Chrome

I have recently started learning CSS and am facing an issue with the alignment of radio buttons. They do not align properly in Chrome and Firefox, although they display correctly in Explorer. Any assistance on this matter would be greatly appreciated. Th ...

Adding a function to the Window in React & Next.js without using the onload event

Issue with External Script in React Next.js Project I am facing a problem with an external script within my React Next.js project. The script is located at . The script does not work correctly when navigating to the page using the next/link component fro ...

Using Regular Expressions for Validation

As a designer trying to set up a payment page without strong developer skills, I've hit some roadblocks. The payment company gave me guidance that involved using regular expressions for validating the 'AMOUNT' field, but my attempts to modif ...

Switch back and forth between adding and removing a table row using jQuery

Currently, I am developing a drop-down feature for a table that populates its data using MySQL. The functionality involves creating a new table row below the current one when a user clicks a button. However, instead of generating multiple new rows each tim ...

Ways to calculate the memory utilization of a JavaScript object

Suppose I want to compare the efficiency of storing bits of a static canvas/image with Alpha more or less than 0.5 using an "array of array of number" versus an "array of string," which would be better in terms of memory usage and speed? var c = $('m ...

Unify your navigation with Bootstrap 5 - harnessing the power of two navs

I am struggling with a code that has three identical blocks, each with at least two navigation items and one tab content. The issue I am facing is that I can't figure out how to deselect the active item in the other lists when one is clicked on. I c ...

Troubleshooting: jQuery script encountering issues with loading Bodymovin JSON files

The animations for the slider and shuffle lottie are designed to go from 0 to 100 and then back to 0 when toggled, similar to the box animation. However, it appears that the slider animation disappears in the final frame while the shuffle animation appear ...

Determine using Lodash whether there is an object in an array that matches the ID from a separate array

There is a user array defined as follows: var users = [{ id: 1, name: 'ABC', isDisplay: true }, { id: 2, name: 'XYZ', isDisplay: true }, { id: 3, name: 'JKL', isDisplay: true }]; Additionally, there is another arra ...

Preloading not working in Bootstrap Ajax Tabs

I've encountered an issue with Bootstrap Tabs and Jquery in my Asp.net MVC5 web app. Tab 1 (30days) is not loading on page load despite my efforts to troubleshoot the code multiple times. Could someone please review and identify where I may be going w ...

When ran automatically as a cron job, the JavaScript script fails to establish a connection with MongoDB

As I connect to mongodb (on a Ubuntu machine) from a js script, everything runs smoothly when I execute the command from the command line (node <name of the script>). However, when I try executing the same command from cron, the connection times out: ...