How to remove an attribute from an array of JSON objects in typescript

I'm currently working with an array of data and my goal is to remove any attributes from the objects where they are null. For example, I want to delete the img attribute from the 3rd object. Here is the approach I have taken so far:

var data = [{
    id: 1,
    name: 'name1',
    img: 'car1'
  },
  {
    id: 2,
    name: 'name2',
    img: 'car2'
  },
  {
    id: 3,
    name: 'name3',
    img: null
  }
]
data.forEach(function(value) {
  for (var key in value) {
    if (value.hasOwnProperty(key)) {
      var val = value[key];
      if (val == null) {
        delete data[value[key]];
      }
    }
  }
});

console.log(data);

However, I am facing an issue with the deletion process not happening as expected. Can anyone provide insights on what might be going wrong?

Answer №1

let information = [{
    id: 1,
    title: 'title1',
    image: 'image1'
  },
  {
    id: 2,
    title: 'title2',
    image: 'image2'
  },
  {
    id: 3,
    title: 'title3',
    image: null
  }
]

information.forEach(info => {
  Object.keys(info).forEach(key => {
    if (info[key] == null) delete info[key];
  });
});

console.log(information);

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

State remains stagnant following update from use state

Recently diving into React, I've been experimenting with getting my socket io listener up and running smoothly. Interestingly, when I have it placed outside of the useEffect, it seems to function but gets called multiple times. However, when nestled w ...

Infinite reload loop triggered by Angular GET method in HTML integration

I am currently tackling a project that involves populating a dynamic number of buttons with links to documents for opening them. <tr *ngFor="let competence of competences; let i = index">{{competence.name.de}} <td *ngFor="let competenceLevel of ...

Choosing a subset of data within a JavaScript object with the help of jQuery/jHashtable

Here is an object that I am working with: var data = { "info" : [{ "title": "Desemberkonsert", "description": "MangerFHS 09/10" }], "playlist" : [ { "title": "In This Place", "description": "Excalibur", "href": "desemberkonsert_in-this-place", "url": "flv ...

Using JSON Zip Response with Node.js

Hi there! I'm relatively new to working with node.js and I'm currently attempting to send a zip file containing JSON results, but I've been encountering some unexpected difficulties along the way. My tech stack includes NodeJS, ExpressJS, L ...

Using JavaScript to invoke a jQuery function

I'm currently working with jQuery and JavaScript, and I have a requirement where I need to invoke a jQuery function from within my JavaScript code. This is the jQuery function in question: function showData(id){ $.ajax({ type:'POST& ...

What is the proper placement for a function in a React application?

Apologies for what might seem like a silly question, but I've been searching high and low for a solution to no avail. I have a handleClick function that is supposed to modify the className of my navbar - adding links and displaying three lines when i ...

Searching for multiple values using ng-model in AngularJS is a powerful feature that allows

I've looked everywhere for a solution to my problem but I haven't found an exact match. Can anyone lend a hand? Here's the ng-repeat filter list I'm working with: <ul> <li ng-repeat="f in filterOptions"> <p>{{f ...

Using the record key as the index for the function argument type

In my current setup, I have : const useFormTransform = <T>( formValues: T, transform: Partial<Record<keyof T, (value: T[keyof T]) => any>>, ) => ... This is how it's used : type Line = { id?: string; fromQuantity: number } ...

When I try to refresh the page in Angular 8 by pressing CTRL + R, it automatically directs me back

Every time I refresh the page using CTRL + R or F5, or open a new tab, it always redirects to the homepage in my Angular 8 application. Here is my Routes setup: const routes: Routes = [ { path: 'dashboard', component: OrderComponent, canActiva ...

What is the process for toggling the expansion and collapse of a table row (tr)?

Based on my previous experience (such as this example), I have observed that a div container can be easily toggled to hide and show. However, I am facing confusion when I have content inside a tr and I wish to display and hide certain items when that tr is ...

The leave animation for Angular's ngAnimate and ng-view feature appears to be malfunctioning

angular version: 1.6.1 I am attempting to create a fade in/out effect for my ng-view element, however, I am encountering an issue where only the enter animation is functioning properly. This is the relevant HTML code: <main class="main" ng-view>&l ...

Is there a way to launch my JavaScript project locally and have index.html served on an npm server?

I am currently attempting to launch a specific Single Page Application (SPA) project using pure JavaScript. This project consists of a script file and an index.html file. I am trying to run this project on my local machine, but it requires that it be hos ...

Having trouble understanding how to properly use the .filter() method in JavaScript, specifically when it comes to using the AND/OR operators? Would appreciate some guidance on

I am currently facing an issue in retrieving my data. I need to exclude any data that has an invoice_status of "Draft", "Ready to Bill", "Cancelled", or if both invoice_status and status are null. Although everything else is ...

Embedding images in Angular using libraries

I am in search of a solution to include images within the Angular Component Library using img[src]. The library successfully locates images from the assets folder for background-image, but when attempting to insert images into img[src], it seems to encount ...

The IDE is able to detect interface extensions in d.ts files, but TypeScript is not recognizing them

When developing in ES6 style module inclusion within WebStorm, I encountered an issue with my Express app and a custom d.ts file. The d.ts file contains middleware that alters objects, and the structure looks like this: declare module Express { export ...

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Is it advisable to utilize Firebase cloud functions in this situation?

Currently, I am developing an expense manager app that utilizes Firebase Realtime Database to store data. The structure of my data on Firebase is as follows: { Txns:[ {s:"x", amount:1000 }, {x:"x", amount:2121 }, ... ], ...

An error occurred when trying to set a cookie using Set-Cookie in a react application

Currently, I am immersed in a small project that involves user authentication via email and password before gaining access to their individual profiles. The backend operates on cookies which are established once the correct email and password combination i ...

The toggle button requires two clicks to activate

I created a toggle button to display some navigation links on mobile screens, but it requires two clicks upon initial page load. After the first click, however, it functions correctly. How can I ensure that it operates properly from the start? Below is t ...

Tips for interpreting JSON content within a C# HttpPost function

I need assistance with extracting data from a JSON body and then displaying it in an HttpPost method using C#. The JSON payload includes: { "name": "John", "age": "20" } [HttpPost] public async Task<IAct ...