How can you upload information while specifying the status?

Within my config.ts file, the contents are as follows:

export const keyOrders: {} = {
    "aa": { active: true, order: 0 },
    "bb": { active: true, order: 1 },
    "cc": { active: true, order: 2 },
    "dd": { active: true, order: 3 },
    "ee": { active: false, order: 4 },
    "ff": { active: true, order: 5 }
};

My objective is to add keys to an array only if their 'active' value is true. The code snippet I have attempted is able to push keys if they are 'active', however, it returns 'undefined' for keys with 'false' values.

public keys = [];
public keyOrders = keyOrders;

ngOnInit() {
     this.keys = Object.entries(this.keyOrders).map((a: any) => {
            if(a[1].active == 'true') {
                return a[0];
            }
        });
}

Answer №1

To achieve this, use the combination of filter and map.

If you need to arrange the items based on their order property, make sure to apply sort before using map.

The role of filter is to retain only the items that meet the given predicate, such as having a truthy active property. Then, map can transform this filtered array into the desired result.

In your scenario, employing map directly would result in an array of equal length, hence the necessity for filtering beforehand.

type Order = { active: boolean, order: number };

const keyOrders: { [key: string]: Order } = {
  "aa": { active: true, order: 0 },
  "bb": { active: true, order: 1 },
  "cc": { active: true, order: 2 },
  "dd": { active: true, order: 3 },
  "ee": { active: false, order: 4 },
  "ff": { active: true, order: 5 }
}

this.keys = Object.entries(this.keyOrders)
  .filter(([_, val]) => val.active)
  .sort((a, b) => a[1].order - b[1].order)
  .map(([key, _]) => key);

To ensure proper typing, make sure Typescript recognizes Object.entries() by including "lib": [ "es2017.object" ] in your tsconfig.json file.

An example of the JavaScript implementation without types:

const keyOrders = {
    "aa": { active: true, order: 0 },
    ... (remaining text unchanged for brevity)
};

const keys = Object.entri... (remaining text unchanged for brevity)
  .map(([key, _]) => key);

console.log(keys);

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 facing an issue in my Nextjs project where the Array Object is not being properly displayed

Hi there! I am new to Nextjs and currently learning. I recently created a component called TeamCard which takes imgSrc, altText, title, designation, and socialProfile as parameters. However, when attempting to display the socialProfile object array using m ...

Webpack encounters an error while attempting to load Bootstrap v4.0.0-beta

I've encountered an issue with my webpack configuration and Bootstrap v4.0.0-alpha.6 that was working fine until I attempted to switch to v4 beta. Unfortunately, I can't seem to get it working properly now :( Here is a snippet of my config: w ...

Is it possible to display a variety of color schemes in just one console.log()?

My task involves working with an array of hexadecimal values, "colors": ["#d5dd90","#e6bb45","#ef9770"] To log these out in different colors, I used the following method: colors.forEach((value)=>{ console.log(& ...

Angular2's integration of backend API calls

My backend calls are functioning correctly, but I'm encountering an issue with promises. I am unable to retrieve the data from the first promise in order to make the second call. Any insights on where I might be going wrong? login() { if (thi ...

The command 'var' is not recognized as an internal or external command within npm

I need assistance with installing the histogramjs package. The command npm i histogramjs successfully installs it, but when I attempt to run the code using var hist = require('histogramjs'), I encounter an error in the command prompt: 'var& ...

FlexSlider in WordPress is failing to display captions

Before pointing out any similar questions, please note that the answer from those sources does not apply to my specific code. I am trying to achieve this through a function as outlined here But I am struggling to figure out how to add captions only if th ...

Sorting the Czech alphabet with the help of Tablesorter

Utilizing the tablesorter characterEquivalents extension as outlined in this documentation. I have created a similar extension for Czech characters, but the sorting is not functioning correctly for certain characters - like \u017d $.extend( $.tables ...

Having trouble with animation transition in Angular 6?

When it comes to animating the opening and closing of a Sidenav, what are some best practices? animations: [ trigger('slider', [ state('open', style( {} )), state('closed', style( ...

Receiving undefined from a file object in JavaScript results in a function error

Struggling with reading the content of a file and storing it into an array for processing. Here's my current approach: let theFile = document.getElementById("getFile"); let fileVal = theFile.files[0]; let dataFromFile = fileVal.getAsDataURL(); alert( ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

Encountered a problem when implementing flowbite in a project using NextJS and TypeScript

I recently added tailwind and flowbite to my NextJS project. After importing "flowbite" in the _app.tsx file, I encountered the following error message: ReferenceError: document is not defined at Object.366 (D:\shopflo\next-tailwin ...

Typescript: The property isComposing is not found on Event type

While working on a React app with Typescript, I encountered a Typescript error both during compile time and in the editor: TS2339: Property isComposing does not exist on type Event This issue arises when handling an OnChange event in an HTML Input element ...

Include a class in the <code> element if it is not nested within a <pre> tag

I am incorporating the Highlight.js script on my website built with DocPad. I am looking to enhance the appearance of a basic <code> tag (equivalent to `` in Markdown), but this conflicts with the existing styles applied by Highlight.js. Highlight. ...

Implementing Event Listeners for buttons generated dynamically

Currently immersed in an exciting side project and encountered a small hiccup. Essentially, I have a page where users can log in to Spotify. Upon login, they are redirected to a page showcasing their top 10 artists in individual cards, complete with the ar ...

Simultaneous activation of two click events in Javascript

I am looking to create a game using JavaScript. The game will be designed for two players to play on the same mobile device. I am facing a challenge with coordinating the players' clicks, as they may happen simultaneously. I have attempted to use bot ...

Error: The filter argument must be in object form

Currently I am in the process of developing a REST API with an endpoint for posting movies. The request body is expected to contain only the movie title, which needs to be validated for presence. Upon receiving the title, I need to fetch other movie detail ...

Can dynamic data be loaded on page load and children on click without storing children in the parent's state?

I have a dilemma with loading dynamic data on my fiddle. You can check it out here: https://jsfiddle.net/61qxn7av/2/ The issue is that each parent should have different children and these children need to append to the correct parent based on which checkb ...

Angular 8: Efficiently Applying Filters to JSON Data Stored in LocalStorage

In my Angular 8 project, I am storing data in localStorage and need to filter it. However, I am unsure about the method to use. Here is how the localStorage values look: [{id: 9, designation: "spectacle + restaurant", gift: [], type: "Soirée Bon plan", ...

Concealing a section of a table with JavaScript while preserving the original table structure

I made some adjustments to the script tag: $(document).ready(function) { Now, the evenTd's are hidden correctly. Here is the table with the code provided: <table> <tr> <td>itemOne</td> <td class="even ...

Registering a component in Vue.js and checking for errors in component registration

Recently, I attempted to use the vuejs-countdown-timer component in one of our projects but encountered an error. Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option. The ...