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

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Unable to leverage vscode workspace path for the next js 13 project

I am facing an issue with TypeScript despite having the latest versions installed in my project (TypeScript 5.2.2 and @types/react 18.2.21): Next 13 — client and async server component combined: 'Promise<Element>' is not a valid JSX elem ...

Transform object into data transfer object

Looking for the most efficient method to convert a NestJS entity object to a DTO. Assuming the following setup: import { IsString, IsNumber, IsBoolean } from 'class-validator'; import { Exclude } from 'class-transformer'; export clas ...

The element body-component is not recognized within the Angular quickstart framework

My attempt at a simple code isn't working as expected. I have some knowledge of angular, but I'm getting frustrated with this issue. ;( Here is the structure of my code: <body-component></body-component> In my body.component.html f ...

best method to pass byte array to ListBlockingQueue

Given that I am handling an array of bytes passed to me, not by choice but out of necessity. My task is to transfer the data to a LinkedBlockingQueue and ultimately iterate through the bytes to construct one or multiple XML messages (which may potentially ...

Utilizing TypeScript in an AngularJS (1.x) project alongside Webpack: A Step-By-Step Guide

Currently, I am working through the official guide on transitioning from AngularJS (1.x) to Angular (2+). I have successfully divided my application into Components and integrated ES6 with Webpack as the module loader. However, I now find myself unsure of ...

Error message in Angular states that it is not possible to bind to 'formGroup' because it is not recognized as a property of 'form' within Angular

When trying to extract data from a form using formcontrol, everything seems to be working fine except for the [formcontrol] = "userForm" in the HTML. If I remove this part, the project runs smoothly. I have tried multiple tutorials but none of them seem ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

What is the best way to produce a random integer within the range of 0 and 2

Here is the code snippet: var i = prompt('Please choose Rock, Paper or Scissors:'); var b = ['Rock', 'Paper', 'Scissors']; Now, I need help in generating a random number between 0-2. My initial idea was to do t ...

Error encountered with react-query and UseQueryResult due to incorrect data type

I'm currently implementing react-query in my TypeScript project: useOrderItemsForCardsInList.ts: import { getToken } from '../../tokens/getToken'; import { basePath } from '../../config/basePath'; import { getTokenAuthHeaders } fr ...

What is the best way to break a string based on a specific delimiter?

I'm trying to retrieve data from the API at and the element I'm working with is in the format of [ 12 +14 +2 +8 ]. My goal is to extract each individual value from this string and display them separately in an array. Initially, I attempted to u ...

What steps should be followed in order to generate a child or item with no assigned key

Here is my TypeScript code designed to automatically record the time of data creation: import * as functions from 'firebase-functions'; export const onAccCreate = functions.database .ref('/Agent/{AgentID}') .onCreate((snapshot, contex ...

Can this be executed in PHP?

Can this code snippet work in PHP? foreach (function() { return ['key' => 'Value']; } as $key => $val){ $new_array = array('Key' => $key, 'Value' => $val); } I am interested in mo ...

Building a seamless service across all components in Angular4

In every service, there is a need for a shared common service that will only be created once. For example, let's call this common service - export Class CommonService { _commonVar1= ""; _commonVar2= ""; } Now, the instance of the common ...

Having trouble getting the Angular2 boilerplate to start with npm?

Just starting out with Angular2 and attempting to set up the environment using the boilerplate code found at https://github.com/mschwarzmueller/angular-2-beta-boilerplate. After successfully installing my dependencies with npm install, I encountered some ...

Encountering a problem where the alert popup does not appear when refreshing Chrome for the first time on the homepage in an Angular application

Firstly, I want to express my gratitude for your response to my previous inquiry. I am currently encountering an issue. When landing on the homepage for the first time, the alert popup does not work. However, once inside the application, it functions prop ...

Implement a call feature using ReactJS

My service method involves making a PUT call to an API with an ID parameter. However, I am facing issues with hitting the .put URL. Can someone please verify if this is the correct approach? ENDPOINTS = { SAMPLE: "/sample", }; Below is my ...

What issues are there with JavaScript?

I encountered an issue with my JavaScript code where it is not producing the expected result. var arr = new Array(); var firstobj = { cta: 0, ccc: 0, crc: 0 } for (var ta = 1; ta <= 10; ta++) { arr[ta] = firstobj; } arr[6].cta = 1; conso ...

Unravel the JSON data array and seamlessly add it to a MySQL database

Looking for some help here as I am struggling with extracting Json data and inserting it into a MySQL database using PHP. Any assistance would be greatly appreciated. {"CityInfo":[{"CityCode":"5599","Name":"DRUSKININKAI"},{"CityCode":"2003","Name":"KAUNAS ...

exploring alternatives to ng-container in angular-4.x for selecting elements

Currently in my Angular 4.x project, I have a component using the Selector 'abc' as shown below: @Component({ selector: "Abc", templateUrl: "Abc.html", styleUrls: [ "Abc.css" ] }) However, the "Abc" tag is also present in the DOM, b ...