Tips for eliminating the undefined object from an array using Angular

let dataArr = [{
    "name": "",
    "columns": [
      {
        "data": "test1",
        "type": "",
        
      },
      null,
      {
        "data": "test1",
        "type": "",
      }
    ],
    "info": "value",
    
  }]

In the array of objects shown above, there are some undefined or null values that need to be removed.

Answer №1

To achieve this, you can utilize a combination of Array.map(), Object.keys(), Array.reduce(), Array.isArray(), and Array.filter() (with the core piece) demonstrated in the code snippet below:

let myArr=[{
    "name": "",
    "columns": [
      {        
        "data": "test1",
        "type": "",        
      },
      undefined,
      {
        "data": "test1",
        "type": "",
      }
    ],
    "info": "value",    
  }]
  
myArr = myArr.map(o => Object.keys(o).reduce((acc, key) => {
  let value = o[key];  
  if (Array.isArray(value)) {
    value = value.filter(o2 => o2);
  }
  acc[key] = value;
  return acc;
}, {}));

console.log(myArr);

Answer №2

Give this a shot

The code snippet below will remove any undefined elements from the 'columns' array within myArr[0]: 
myArr[0].columns = myArr[0].columns.filter((data)=>data!==undefined);

Use this to clean up any undefined values in the columns array effectively

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

React state array fails to update

I'm facing an issue while updating my state with a new array. The console shows no errors and correctly prints out the newly formed array, but the state doesn't reflect this update. What am I missing here? state = { notes: [ { ...

Array failing to populate with accurate information

During the loop, I am populating an array: for k in one two three; do array+=( "$k" ) done echo $k[0] # Expecting to print 'one', but prints 'one[0]' echo $k[1] # Expecting to print 'two', but prints 'one[1]' W ...

'Error: The type is missing the 'previous' property - Combining TypeScript with ReactJS'

I am quite new to using reactjs and ts. While I understand the error that is occurring, I am unsure of the best solution to fix it. Currently working with reactjs, I have created an: interface interface IPropertyTax { annul: { current: number; p ...

The challenge of generics in Typescript: destructuring and spreading

I am facing an issue with destructing parameters and creating a new object of the same type in Typescript. The following code functions properly: function customFunc<T extends { attribute: string }>(parameter: T): T { const { ...rest } = paramete ...

Collect a string, break it apart, and store it in a C# array

I'm attempting to take input from the user in the form of a string and store it in an array. The string must consist of single-digit numbers separated by spaces, with exactly 20 numbers entered where no number can repeat consecutively. For example: ...

How can you tell if a numpy array is of the datetime64 data type?

I have a numpy array and I need to determine whether it contains datetime64 values or just normal numeric values. This is important for my plotting functions that can accept both types of arrays, but operations like np.isnan or np.isinf don't work on ...

What is the process for configuring PhpStorm to sync with TypeScript tsconfig.json in .vue files?

Vue.js (webpack + vueify) with TypeScript is my current setup. The ts configuration appears to be functioning, but only in .ts files. For instance, in tsconfig.json: "compilerOptions": { "strictNullChecks": false, So strictNullChecks works as expect ...

Discover how to automatically determine type based on a constant property value in Typescript

I need to determine the type of a property from a predefined constant. const my_constant = { user: { props: { name: { type: 'string' } } }, media: { props: { ...

Utilize ngx-translate in Ionic 2 for translating menu items

I have successfully implemented ngx-translate for multi-language support in my application. However, I am now looking to extend this functionality to my menu items. How can I achieve this for my 3 menu items with different titles? ts file appPages: Pag ...

No defined window.XMLHttpRequest

My node.js application was designed to parse the HTML AST and Typescript AST of angular2 in order to extract necessary data. In order to accomplish this, I needed to import @angular/compiler and subsequently @angular/core, which has a peerDependency of zo ...

Generate an Observable<boolean> from a service function once two subscriptions have successfully completed

I am working on setting up a simple method to compare the current username with a profile's username in an Angular service. It is necessary for the profile username and user's username to be resolved before they can be compared. How can I create ...

What is the most effective way to decode a JSON formatted multidimensional array of checkboxes?

Uncertain if the Title was accurate, the actual application is a quiz. Let me provide an example with this sample snippet. <form method="POST"> Softdrinks: <div class="checkbox"> <label><input type="checkbox" ...

Issue arising from using setCollideWorldBounds and overlap in Phaser 3

I'm facing an issue with Phaser 3. Whenever I use setCollideWorldBounds, I get an error saying "Cannot read property 'setCollideWorldBounds' of null" and the overlapping function doesn't seem to work. What's even more strange is t ...

Errors related to reducer types in createSlice of Redux Toolkit

As I embark on a new React-Redux project with Typescript, I find myself facing some challenges despite my previous experience. While my knowledge of React and Redux is solid, I am still getting acquainted with Redux toolkit. Transitioning from a typed back ...

technique that can hold a maximum of 100

I seem to be having trouble creating this class properly. I'm encountering an error with the array I'm trying to create and I'm not sure how to resolve it. The compile error is ArrayList<Vehicle> db = new ArrayList<Vehicle>(); I ...

Circular dependency in Typescript/Javascript: Attempting to extend a class with an undefined value will result in an error,

Query Greetings, encountering an issue with the code snippet below: TypeError: Super constructor null of SecondChild is not a constructor at new SecondChild (<anonymous>:8:19) at <anonymous>:49:13 at dn (<anonymous>:16:5449) ...

What are some ways to customize formControlNames in Angular reactive forms?

Is there a way to customize the formControlName in Angular forms? I need to be able to toggle check-boxes on and off based on certain values within a nested object array. Here is an example of what the HTML code might look like: <span class="col-md-2" ...

Issue with Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object'. NgFor is only compatible with binding to Iterables such as Arrays

As someone who is new to Angular, I am facing a challenge while working on my portfolio project. The issue arises when trying to receive a list of nested objects structured like this: "$id": "1", "data": { &quo ...

What's the best way to define the data types for a component that utilizes the set function?

This code snippet seems to be functional, but there are some issues with the types that need to be resolved before it can be compiled successfully. Here is the code in question: function SpotlightElement(props: JSX.IntrinsicElements['spotLight'] ...

Securing Angular 2: How to Safely Store PassportJS Tokens

How can I retrieve the token generated from the provided express code snippet after a user logs in via Facebook, is stored in the database, and is redirected to /auth/facebook/callback? I want to fetch this token using either callbacks, promises, or obse ...