Eliminating null values from a multidimensional array

Is there a way to remove the array elements cctype, cctypologycode, and amount if they are empty? What would be the most efficient approach?

{
  "ccInput": [
    {
      "designSummaryId": 6,
      "CCType": "A",
      "CCTypologyCode": "A",
      "Amount": "1"
    },
    {
      "designSummaryId": 7,
      "CCType": "",
      "CCTypologyCode": "",
      "Amount": ""
    },
  ]
}

ccInput[1] needs to be removed from the array

Answer №1

To eliminate certain elements from an array, utilize the Array.prototype.filter() method.

If you prefer to maintain immutability, you can achieve this by making a copy of each object property using the spread operator and then filtering based on the ccInput property:

const obj = {ccInput:[{designSummaryId:6,CCType:"A",CCTypologyCode:"A",Amount:"1"},{designSummaryId:7,CCType:"",CCTypologyCode:"",Amount:""}]};

const result = { ...obj, ccInput: obj.ccInput.filter(x => x.CCType && x.CCTypologyCode) };

console.log(result);

Alternatively, if you want to directly modify the object, simply update the ccInput property:

const obj = {ccInput:[{designSummaryId:6,CCType:"A",CCTypologyCode:"A",Amount:"1"},{designSummaryId:7,CCType:"",CCTypologyCode:"",Amount:""}]};

obj.ccInput = obj.ccInput.filter(x => x.CCType && x.CCTypologyCode);

console.log(obj);

Answer №2

When it comes to TypeScript, my knowledge is limited, but I am aware that you have the option to initialize an array with []. If you are trying to remove only a specific section of an array without clearing the entire thing, one straightforward method I recommend is to set each element to a neutral value - such as 0 for numbers, '' for characters, "" for Strings, and so on.

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

Substitute all properties of a specific type with a predetermined value in Typescript using recursive substitution

If we consider the given type structure: type Person = { name: string age: number experience: { length: number title: string } } Can we create a type like this: type FieldsOfPerson = { name: true age: true experience: { length: t ...

What's causing the malfunction of Angular subscriptions when switching between tabs?

I have developed a basic angular application that necessitates users to authenticate for WebEx in order to obtain an access token. The access token is stored in the local storage using a simple GET API. My goal is to implement a flag or status at the app. ...

Obtaining child component references in Angular using @ViewChildren

Currently, I am generating several ModuleItemComponents by utilizing the following Angular syntax: <div #moduleItems *ngFor="let module of seriesItem.modules; let i = index"> <app-module-item [videoModule]="module" >< ...

How come my button is initiating automatically instead of manually?

Working on developing an API using Angular 2 with the Janus media server has brought up an issue regarding the start button. When running Janus, the button initiates automatically instead of manually. The following function was implemented for this purpos ...

Tips for integrating material icons into your project

Having some trouble using Outlined material icons in my application. Struggling with the import process and can only access the normal filled icons instead of the outlined ones. I would like to incorporate outlined icons similar to those shown in this exam ...

Issue: The element '[object Object]' is of type 'object', which is not supported by NgFor. NgFor only works with Iterables like Arrays. - Problem encountered in an Ionic Project

I'm currently working on retrieving my user's username from Firebase Firestore Database using Ionic and AngularFire. I have implemented the valueChanges() method to obtain the observable and am trying to process it using an async pipe. However, u ...

Utilizing v-for in Vue with TypeScript to generate multiple checkboxes

My goal was to capture the values of checkboxes and store them in an array using v-model. However, I encountered an issue where the first time I toggle a checkbox, it doesn't register. Only after checking a second box and hitting submit does the secon ...

Extract data from an HTTP request and assign it to variables using filter and map in Angular

I need to extract data from an http get request and assign it to 3 separate variables once fetched. Data: [ { reportId: 1, results1: [{ name: "TotalReferralsMade", optionId: 3082, factor: 1, description: null ...

New Requirement for Angular Service: Subclass Constructor Must Be Provided or Unable to Resolve all Parameters for ClassName (?)

During a recent project, I encountered an issue while working on several services that all extend a base Service class. The base class requires a constructor parameter of HttpClient. When setting up the subclass with autocomplete, I noticed that their con ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

The test suite encountered an error (EBUSY: resource busy or locked) and unfortunately failed to run at Nx version 14.5.10 and Jest version 27.5.1. It seems there was an

I have recently upgraded my NX Monorepo from version 13 to 14, and everything seems to be working fine except for the Jest migration. I keep encountering this error even after trying various solutions like clearing the cache, deleting node_modules, and rei ...

After updating to ionic-native 2.5.1, encountering TypeScript Error TS1005 in Ionic 2

After updating to the latest version of ionic-native (2.5.1) in my ionic 2 project, I am encountering Typescript errors when running "ionic serve" in my terminal. I have attempted to update the typescript version to 2.x but to no avail. Any assistance woul ...

Tips on utilizing the `arguments` property in scenarios where Parameters<...> or a similar approach is anticipated

How can you pass the arguments of a function into another function without needing to assert the parameters? Example: function f(a:number, b:number){ let args:Parameters<typeof f> = arguments // Error: Type 'IArguments' is not assignab ...

Organize an array of objects with underscore.js to arrange them in a

I have an array of objects that looks like this: profData=[{"Details":{"CODE":"PAT4PAS","DESCRIPTION":"PASTIE 4N20 12 X 175G","LOCATION":"FREEZER","UNITS":"BOX","WAREHOUSE":"00","AVAILABLE":"15.0000","ON_HAND":"15.0000","BRAND":"4N20","PRICE1":"18.80"," ...

Encountering a TS(2322) Error while Implementing Observables in Angular 12

Exploring the intricacies of Angular 12 framework, I find myself encountering a hurdle in my learning journey. The tutorial I am following utilizes the Observable class to query fixed data asynchronously. However, an unexpected ts(2322) error has surfaced ...

Troubleshooting History.push issue in a Typescript and React project

Currently, I'm tackling a project using React and TypeScript, but I've encountered a problem. Whenever I attempt to execute a history.push function, it throws an error that reads: Uncaught (in promise) TypeError: history.push is not a function. ...

Utilizing Angular: Importing Scripts in index.html and Implementing Them in Components

Currently, I am attempting to integrate the Spotify SDK into an Angular application. While I have successfully imported the script from the CDN in index.html, I am encountering difficulties in utilizing it at the component level. It seems like there may be ...

Why is Axios not being successfully registered as a global variable in this particular Vue application?

Recently, I have been delving into building a Single Page Application using Vue 3, TypeScript, and tapping into The Movie Database (TMDB) API. One of the hurdles I faced was managing Axios instances across multiple components. Initially, I imported Axios ...

Creating OL maps with subpar quality using the Ionic framework

I'm currently facing an issue while trying to load the OL map with Ionic. When I use 'ionic serve' to load it, the map displays perfectly in the browser. However, when I try to load the map on a mobile device, the quality drastically decreas ...

Discovering identical objects in two arrays in Angular using TypeScript is a breeze

I've hit a roadblock with a TypeScript problem in my Angular service. I have an array of ingredients: private ingredients: Ingredient[] = [ new Ingredient('farina', 500), new Ingredient('burro', 80), new Ingredient('ucc ...