Forming a distinct array from a collection of objects

Describing demoList:

demoList = [
    {
      id: 1,
      validFrom: "2019-06-01T00:00:00",
      validTo: "2020-06-17T00:00:00",
      xxxM: 50,
      xxxN: 2.2,
      xxxQ45: 2,
      xxxQ100: 1.65,
      xxxQ125: null,
      xxxQ150: null,
      xxxQ250: null,
      xxxQ300: null,
      xxxQ500: null
    },
     {
      id: 2,
      validFrom: "2019-06-01T00:00:00",
      validTo: "2020-06-17T00:00:00",
      xxxM: 51,
      xxxN: 22,
      xxxQ45: 1.4,
      xxxQ100: 1.65,
      xxxQ125: null,
      xxxQ150: 1.7,
      xxxQ250: null,
      xxxQ300: 0.15,
      xxxQ500: null,
      xxxQ700: 15.4
    },
   . . .
];

The desired array:

["M", "N", "45", "100", "150", "300", "700"]

I am looking for a way to extract an array of non-empty values starting with xxx from the demoList in angular. How can this be accomplished?

Answer №1

To process your demoList objects in a specific way, you can utilize a combination of array manipulation methods in JavaScript. By using the .flatMap() method, you can flatten the objects into an array and then access their key-value pairs with Object.entries(). Filtering out entries that begin with "xxx" and have a non-null value can be achieved with the .filter() method. Next, you can extract relevant information from the keys by matching them with a regular expression pattern using .match(/\d+|\w$/g). To eliminate duplicates, you can convert this manipulated array to a Set and then reconvert it back to an array using the spread operator:

const demoList = [{ id: 1, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 50, xxxN: 2.2, xxxQ45: 2, xxxQ100: 1.65, xxxQ125: null, xxxQ150: null, xxxQ250: null, xxxQ300: null, xxxQ500: null }, { id: 2, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 51, xxxN: 22, xxxQ45: 1.4, xxxQ100: 1.65, xxxQ125: null, xxxQ150: 1.7, xxxQ250: null, xxxQ300: 0.15, xxxQ500: null, xxxQ700: 15.4 } ];

const res = [...new Set(
  demoList.flatMap(Object.entries)
          .filter(([k, v]) => k.startsWith("xxx") && v !== null)
          .map(([k]) => k.match(/\d+|\w$/g).pop())
)];

console.log(res);

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

In Angular Mat Stepper, only allow navigation to active and completed steps

For a project, I created a sample using React.js and Material UI. Here is the link to the project: https://stackblitz.com/edit/dynamic-stepper-react-l2m3mi?file=DynamicStepper.js Now, I am attempting to recreate the same sample using Angular and Material, ...

Exploring an array of intricate objects to find specific attributes and extracting an array of corresponding values

Trying to search an array of complex objects for specific attribute values in a flat array presents a challenge. Despite numerous attempts, none of the methods tried so far have yielded successful results. The objective is to identify and collect all &ap ...

Incorporate a module that was developed locally into your project

Attempting to incorporate a locally developed Angular project/module into an angular application without having to publish it on the npm repository has been quite a challenge for me. To begin with, I decided to follow a tutorial that guided me through bui ...

Encountering an error while attempting to add class-constructed objects to an array list in React/NextJs: "Unable to add property 0, as the object is

This function contains the code required to generate rows for display in a Material Ui table. class User { constructor(id, name, email, measured, offset, paidAmount, status, home, misc, plane, transport, partner, isCoupon) { thi ...

Can Typescript restrict a value to only exist within a specified set of key names within the same object?

I am completely new to Typescript and I am fascinated by the way it can check types. One thing I would like to know is if Typescript can be used to verify at compile time whether a value's domain falls within a predefined set of key names that are de ...

Can an excessive amount of classes cause my Angular application to run sluggishly?

Within my Angular 7 application, I have generated approximately 200 to 300 classes for model types (e.g. component.model.ts) solely for type checking purposes. I have not instantiated any objects from these classes. As I navigate through the application, ...

Sort through an array using criteria from another array

const items = [[{name:"p2"},{name:"p3"}, {name:"p7"},{name:"p9"},{name:"p1"}],[{name:"p6"}, {name:"p3"},{name:"p7"}, {name:"p9"},{name:"p2"}],[{name:"p ...

Using constant variables as arguments in functions in TypeScript

While learning about TypeScript, I encountered some confusion regarding how it handles const variables. Let's consider a scenario where I define an interface for a number: interface MyNumber { value: number; } If I then create a constant MyNumbe ...

"Techniques for incorporating a screen in Angular application (Switching between Edit and View modes) upon user interaction

We are currently working on a screen that requires the following development: This screen will have the following features: When clicking on a button, the fields should become editable. In the image provided, there is some repeated data, but in our case, ...

I recently upgraded my Angular version from 5 to 8, and encountered an unexpected error with the toastr plugin

I recently upgraded my Angular version from 5 to 8 and encountered an issue. Upon starting the server with 'ng serve', I received the following error in the console: Uncaught TypeError: core_1.style is not a function at Object../node_modules/ng ...

Adjust the size of an event in the Angular Full Calendar with Chronofy, while utilizing constraints to control the drag and drop functionality

I'm currently in the process of developing an availability calendar for scheduling meetings during open times. If a time slot is unavailable, users should not be able to place an event there. While I have successfully implemented this feature, I am ...

Module is absent in JavaScript but present in TypeScript

As I delve into coding a vscode extension by following a tutorial, I encountered an issue with importing in my server.ts file. The directory structure looks like this: ...

JavaScript: Obtaining a Distinct Identifier for Various Replicated Entries

Imagine we have an object: var db = [ {Id: "201" , Player: "Jon",price: "3.99", loc: "NJ" }, {Id: "202", Player: "Sam",price: "4.22", loc: "PA" }, {Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" }, {Id: "204", Player: ...

Craft a unique typings file tailored to your needs

After recently creating my first published npm package named "Foo", I encountered some difficulties while trying to consume it in a TypeScript project. The tutorials on how to declare modules with custom typings were not clear enough for me. Here are the k ...

Transforming text values into ArrayLists in Robot Framework: A step-by-step guide

Can someone help me with converting this value to an ArrayList? ${doc1}= Open Excel Document filename=${OpenExcel} doc_id=doc1 ${view_bicccicmdu}= Read Excel Row row_num=1 max_num=6 sheet_name=UpperTT ${view_bicccicmduCheckLength}= ...

Is there a way to make the parent elements invisible when there are no child elements present?

Take this scenario for instance: <ul *ngIf="hasAnyPermission(['A:READ', 'B:READ', ...])"> <li *ngIf="hayPermission('A:READ')"> a </li> <li *ngIf="hasPermission('B:RE ...

Decoding the concept of jQuery Arrays

Creating an array for comparison purposes in the future is my current task. Below is the code snippet used to construct "myArray" for future use: var optionTexts = []; $('#stripeMeSubSubCat tr').each(function(){ if ($(this).find('input: ...

Enforcing uniform data types in nested objects in TypeScript

Currently, I am in need of generating a list of constants. For instance, const Days = { YESTERDAY: -1, TODAY: 0, TOMORROW: 1, } I am looking for a method to restrict the types of all properties within Days. In other words, if I attempt to add a pr ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

Tips for correctly saving an array to a file in node.js express using fs module

I have been attempting to write an array to a file using node.js and angular for assistance, you can refer to the provided code in this question. Whenever I send the array, the file displays: [object Object],... If I use JSON.stringify(myArr) to send my ...