The process of sorting keys in an array of objects according to their values

I am looking to extract keys from an object based on their corresponding values in a key-value pair.

Specifically, I want to filter out the keys that have a value of true.

I attempted to use array.filter, but so far I have not been successful in finding a solution.

For example:

const arry = [{'fname': true}, {'lname': true}, {'country': false}];

Could someone assist me in figuring out how to retrieve keys with true values?

Desired output:

The keys ['fname','lname'] should be returned as they are the only ones with true values.

Answer №1

To simplify the array, you can iterate through each entry and check if the value is true before pushing the key into a new array.

var data = [{ first: true }, { last: true }, { address: false }],
    result = data.reduce((output, item) => {
        var [key, value] = Object.entries(item)[0];
        if (value) output.push(key);
        return output;
    }, []);

console.log(result);

Answer №2

Array.filter is a method that takes a function as an argument, and this function should return either true or false based on whether a specific element from an array should be kept or not.

When dealing with arrays of objects, each object can have multiple keys and values. To process this, you can follow these steps:

  1. Combine all the objects into a single object (be cautious if there are similar keys in multiple objects).
  2. Select the keys from the combined object that have a value of true.

To merge objects, you can use Object.assign method. By utilizing Array.reduce, you can consolidate the array of objects into a singular object:

const combined = arry.reduce((acc, val) => Object.assign({}, acc, val))

Now, you will have a single object containing all the key-value pairs like this:

// { country: false, fname: true, lname: true}

Next, filter out the entries with a true value, resulting in an array of arrays:

const entries = Object.entries(combined).filter(([k, v]) => v)
// [["lname", true], ["fname", true]]

You can then map out the keys from that array as follows:

entries.map(([k, v]) => k)
// ["lname", "fname"]

All these steps can be chained together for a more concise solution.

const arry = [{'fname': true}, {'lname': true}, {'country': false}];

 Object.entries(arry.reduce((acc, val) => Object.assign({}, acc, val)))
   .filter(([k, v]) => v)
   .map(([k, v]) => k)

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

Reducing the file size of a video during the upload process in a JavaScript (React) web application

Within my React application, I have successfully integrated an image and video uploading feature. When it comes to images, I am currently compressing them before they are uploaded to the server. Now, I am facing a dilemma regarding video compression - shou ...

Is it possible to send an array list to a fragment?

I'm dealing with an issue where I need to pass the final List<PieEntry> entries = new ArrayList<>(); to another fragment that is currently empty. Below is my complete code for the fragment initializing the ArrayList: My code goes here... ...

Erase the white backdrop from the dragImage

Is there a way to remove the white outline that appears when dragging a draggable element from a dark background? I want to make it completely transparent. Here is a visual representation: https://i.sstatic.net/Eywf9.png Here is the code snippet: docume ...

Vue-based bot for telegram web application

Hey there, I've been working on integrating a web app with my chat bot, taking advantage of the new Telegram feature. Unfortunately, after adding the site, I'm encountering an issue where clicking the button opens up an empty page. It seems that ...

When I attempt to map imports in Typescript, an error occurs, stating, "Element implicitly has an 'any' type because the expression of type 'string' is being indexed into type 'typeof import'."

(parameter) key: string An issue arises where the expression of type 'string' cannot be used to index type 'typeof import("d:/Projects/Front/attendance-checker2/src/redux/modules/sagas")', leading to an implicit 'any&a ...

Error encountered in NPM MSSQL: unhandled exception - Unable to access property 'release' from a null object

While attempting to establish a connection to the mssql server using the npm mssql module, I encountered the following error. Despite my efforts to find a solution, the issue remains unresolved as it has been previously reported by other users on GitHub. ...

Is there a way to retrieve text content from a modal using JavaScript?

I am using ajax to fetch values from my table. $(data.mesIzinTanimList).each(function (index, element) { if (element.izinTanimiVarmi == 'yok') tr = "<tr class='bg-warning text-warning-50' row='" + element. ...

Applying a dynamic translate3d transformation on the ::after element using CSS3

My current challenge involves manipulating a pseudo ::after element using translate3d If I hardcode the values, it's straightforward: div::after { ... transform: translate3d(40px, 40px, 0); } Now, I want to dynamically set the value for the ...

Use the .replace method to only substitute the initial occurrence

One of the functions I have analyzes a string of content and an array of documents to identify matches. The user is then given the option to accept or reject these matches through another function. However, when the user accepts a match using the acceptLin ...

Incorporating Sass into a TypeScript-enabled Create React App

Having recently transferred a create-react-app to typescript, I've encountered an issue where my scss files are not being recognized in the .tsx components. The way I'm importing them is as follows: import './styles/scss/style.scss'; ...

Oops! You're trying to render a Next.js page using a layout that has already been declared

I have created two different layouts in Next.js - MainLayout and DashboardLayout. import Navigation from '../Navigation'; export default function MainLayout({ children }) { return ( <> <Navigation links={[ ...

Clear form values in react-hook-form upon form closure

Featuring the given component: import { yupResolver } from '@hookform/resolvers/yup'; import { useForm } from 'react-hook-form'; import * as yup from 'yup'; import { useToggle } from '../shared/hooks'; import { Su ...

Scripts that are loaded externally and dynamically are not executed

When integrating an external script to display a streaming webcam in a specific div, the goal is to wait for the user to select a webcam before firing the script. This third-party vendor provides embedding code that includes a div for video display and a s ...

Switch up the header's date format on NGX-Print

Within my application, I am utilizing ngx-print with Angular 8. When I click the print button, a date in the format mm/dd/yy is added to the header. However, I would like to change it to dd/mm/yy. Despite searching, I have been unable to find any document ...

Vue project encountering TypeScript error: Module not found

In my Vue project, I am encountering an issue while using TypeScript. Whenever I try to import a .vue file, I encounter a 'cannot find module...' error. https://i.sstatic.net/jUPGe.jpg The strange thing is that the intellisense only displays t ...

The protected routes within a React JS application consistently result in an undefined value

In my ProtectedRoute component for my react application, I am facing an issue with user authentication. I am using react-router-dom v6 to access the token from localStorage, but no matter what, the user variable always returns undefined. import { Outlet, N ...

"Encountering the 'GetUserByAccountError' issue with Nextjs version 13.4, next-auth version 4.22.1, and @next-auth/prisma-adapter version 1.0.6

What triggers the error GetUserByAccountError when attempting to log in via SocialLogin with Github or Google? Here is a detailed description of the issue: Unknown arg `provider_providerAccountId` in where.provider_providerAccountId for type AccountWhereUn ...

Having difficulty animating camera rotation in ThreeJS with Tween

I am facing an issue with animating the ThreeJS camera rotation using TweenJS. While I can successfully tween the camera position, the camera.rotation does not seem to update as expected. To illustrate my problem, I have created a simple example based on ...

Guide on utilizing the reduce method with objects

I am attempting to use the reduce method on an object to create an HTML list const dropdownTemplate = (data) => { console.log(data); // no data displayed return ` <li class="dropdown__item" data-value="${data.value}"><span class="dropdown__i ...

typescript function not returning the correct value as expected

I am facing an issue with my code where the function to check stock availability through an API call always returns true before the apiMethod.post is executed. It seems like the apiMethod.post evaluation occurs after the if condition. Can anyone provide ...