Removing multiple elements from an array of JSON objects using TypeScript

I am trying to remove specific items from a JSON object using an array in JavaScript:

const addressNonRequired = ["addr_linkid_usr", "addr_created", "addr_updated"]

Instead of using the 'delete' method individually for each item, I want to use the above array. How can I achieve this?

// remove non-required data
addressesFound.forEach(row => (
  // delete row.addr_linkid_usr,
  // delete row.addr_created,
  // delete row.addr_updated
  addressNonRequired.forEach(item => (
    delete row[item];
  ));
));

I have tried different approaches but still struggling to make it work. Maybe I am missing something...?

Here is the sample input array:

[
  {
    "addr_id": "41d86d46-8b19-4f4e-be03-f9915ef4947b",
    "addr_type": "postal",
    "addr_linkid_usr": "user1",
    "addr_created": "2021-03-10",
    "addr_updated": "",
    "addr_active": true,
    "addr_postal_as_residential": false,
    "addr_international": false,
    "addr_autocomplete_id": null
  },
  {
    "addr_id": "b18c2ca6-29cf-4114-9067-b37fd3394638",
    "addr_type": "residential",
    "addr_linkid_usr": "user1",
    "addr_created": "2021-03-10",
    "addr_updated": "",
    "addr_active": true,
    "addr_postal_as_residential": true,
    "addr_international": true,
    "addr_autocomplete_id": "string"
  }
]

The expected output should be:

[
  {
    "addr_id": "41d86d46-8b19-4f4e-be03-f9915ef4947b",
    "addr_type": "postal",
    "addr_active": true,
    "addr_postal_as_residential": false,
    "addr_international": false,
    "addr_autocomplete_id": null
  },
  {
    "addr_id": "b18c2ca6-29cf-4114-9067-b37fd3394638",
    "addr_type": "residential",
    "addr_active": true,
    "addr_postal_as_residential": true,
    "addr_international": true,
    "addr_autocomplete_id": "string"
  }
]

Answer №1

Iterating over the addressesFound array is necessary. Within each object, you must iterate through the keys and compare them to the addressNonRequired array. If a key matches, it should be removed.

var addressesFound = [{
    "addr_id": "41d86d46-8b19-4f4e-be03-f9915ef4947b",
    "addr_type": "postal",
    "addr_linkid_usr": "user1",
    "addr_created": "2021-03-10",
    "addr_updated": "",
    "addr_active": true,
    "addr_postal_as_residential": false,
    "addr_international": false,
    "addr_autocomplete_id": null
  },
  {
    "addr_id": "b18c2ca6-29cf-4114-9067-b37fd3394638",
    "addr_type": "residential",
    "addr_linkid_usr": "user1",
    "addr_created": "2021-03-10",
    "addr_updated": "",
    "addr_active": true,
    "addr_postal_as_residential": true,
    "addr_international": true,
    "addr_autocomplete_id": "string"
  }
];

const addressNonRequired = ["addr_linkid_usr", "addr_created", "addr_updated"];

var updatedAddresses = addressesFound.map(function(address) {
    Object.keys(address).forEach(function(key) { // Iterate through the keys of each address object
    if (addressNonRequired.includes(key)) {
      delete address[key]; // Remove matching keys from the addressNonRequired array
    }
  });
  return address;
});

console.log(updatedAddresses);

Answer №2

One of my frequently used techniques is filtering an object or an array of objects.

I like to keep these functions in my helpers.ts file because they ensure that the keys being filtered actually exist in the object, and they provide autocomplete functionality.

export function except<T, K extends keyof T>(data: T, keys: Array<K>) {
    const copy = { ...data };
    for (const key of keys) {
        if (key in copy) {
            delete copy[key];
        }
    }
    return copy;
}

export function exceptMany<T, K extends keyof T>(data: Array<T>, keys: Array<K>) {
    return [...data].map((item) => except(item, keys));
}

To filter an array of objects, you can use the following:

const data = [
  {
    "addr_id": "41d86d46-8b19-4f4e-be03-f9915ef4947b",
    "addr_type": "postal",
    "addr_linkid_usr": "user1",
    "addr_created": "2021-03-10",
    "addr_updated": "",
    "addr_active": true,
    "addr_postal_as_residential": false,
    "addr_international": false,
    "addr_autocomplete_id": null
  },
  {
    "addr_id": "b18c2ca6-29cf-4114-9067-b37fd3394638",
    "addr_type": "residential",
    "addr_linkid_usr": "user1",
    "addr_created": "2021-03-10",
    "addr_updated": "",
    "addr_active": true,
    "addr_postal_as_residential": true,
    "addr_international": true,
    "addr_autocomplete_id": "string"
  }
];

const results = exceptMany(data, ['addr_linkid_usr', 'addr_created', 'addr_updated']);

You can also filter keys from a single object like this:

const single = {
    "addr_id": "41d86d46-8b19-4f4e-be03-f9915ef4947b",
    "addr_type": "postal",
    "addr_linkid_usr": "user1",
    "addr_created": "2021-03-10",
    "addr_updated": "",
    "addr_active": true,
    "addr_postal_as_residential": false,
    "addr_international": false,
    "addr_autocomplete_id": null
};

const filteredSingle = except(single, ['addr_linkid_usr', 'addr_created', 'addr_updated']);

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

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

using Java Streams to separate values by commas

I have a series of strings, each representing a JSON object like this: // {"foo": "bar", "bar": "foo"} String s1 = "{\"foo\": \"bar\", \"bar\": \"foo\"}"; Due to the large amount of data I receive from the database ...

There is an error appearing in my .ts code: [ts] The property 'name' is not found in type 'any[]'

While my coding is working fine and data is showing on the page, there seems to be an error occurring in the VSE editor. It is showing something like this: [ts] Property 'name' does not exist on type 'any[]'. This is a snippet of my ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

Transforming table data into a JSON format

My goal is to generate a specific JSON format from a table. The table consists of rows and 4 columns. You can view my table here. I aim to create a JSONArray based on the table. The first value in the left column serves as the key in the JSON, while the la ...

Processing JSON data on Android devices

I'm currently facing an issue where I am able to successfully read JSON data, however, I am encountering a problem when trying to add the resulting String into an ArrayList. Are there any suggestions as to why this might be happening? Below is the co ...

Angular - optimizing performance with efficient HTTP response caching tactics

I'm managing numerous services that make requests to a REST service, and I'm looking for the optimal method to cache the data obtained from the server for future use. Can someone advise on the most effective way to store response data? ...

Exporting a Typescript interface from a restricted npm package

I'm working on an npm module using TypeScript that includes several interfaces. In the index.ts file, I export all of the classes and interfaces. I defined the interfaces as "interface dto {a:string;} export default dto". However, when I import the ...

Transform HTML elements within an *ngFor iteration based on a specific variable in Angular 4

In my current project using Angular 4, I am faced with the task of dynamically modifying HTML tags within an *ngFor loop based on a variable. Here is the code snippet that represents my approach: <mat-card-content *ngFor="let question of questionGrou ...

Repairing keys in PostgreSQL JSON format

I am looking to ensure the keys for a JSON object in PostgreSQL (v10.7) are fixed or validated. For example, I have a JSON object named service_config with the following structure; {"con_type": "Foo", "capacity": 2, "capacity_unit": "gbps"} And I have a ...

The member 'pipe' is not found within the 'AngularFireObject<{}>' type

As someone new to Angular, I've been following a tutorial by Mosh Hamedani on version 6 of Angular, but unfortunately the tutorial is based on version 4. Currently, I'm working on an e-commerce project that involves implementing an AddToCart butt ...

refresh Laravel 5.1 webpage content seamlessly without page reloading

Is there a way to update page content in Laravel 5.1 every second without reloading the page for all users? Here is my current view: I'm trying to refresh data without reloading the page using a foreach loop, but I'm not sure how to accomplish ...

When utilizing <number | null> or <number | undefined> within computed() or signals(), it may not function properly if the value is 0

I've encountered an issue while implementing signals and computed in my new Angular project. There's a computed value that holds an id, which is initially not set and will be assigned by user interaction. To handle this initial state, I attempte ...

Tips for inserting information from a JSON file into a mailto hyperlink

As a newcomer to JavaScript, I am eager to tackle the challenge presented below: Situation: In possession of a JSON file containing personal details such as name, email address, bio, etc., my task is to design a basic web page showcasing this data for ea ...

Troubleshooting issue with absolute paths in Vite project using React and TypeScript

I'm having trouble implementing absolute paths in a Vite react-ts project. This is how I set up the project: npm init @vitejs/app npx: installed 6 in 1.883s √ Project name: ... test-vite √ Select a framework: » react √ Select a variant: » rea ...

Using a Powershell script to extract JSON data, validating the value (date) of an object and triggering a specific function if the date is more than x days old

{ "items": [ { "AlertID": 4369, "Code": 52, "Source": "AlphaAgentSelfMonitoring", "Title": "CPU-Temperatur ( (CPU Core #1), (CPU Core #2) und (CPU Package))" ...

Challenges arise when establishing a Django Foreign Key relationship with a CharField data type

Just starting out with Django and using it to build a small APIrest. I've run into an issue while defining the application models. class Localities(models.Model): id = models.BigAutoField(primary_key=True) field_id = models.CharField(unique=T ...

Only one choice for discriminated unions in react props

Looking to create a typescript type for react component props, specifically a basic button that can accept either an icon prop or a text prop, but not both. My initial attempt with a discriminated union didn't quite produce the desired outcome: inter ...

Exploring the Versatility of Jsons with Retrofit and Kotlin

My API is delivering a polyphonic Json where the variable addon_item can be either a String or an Array. I have been struggling for days to create a CustomDezerializer for it, but so far, I haven't had any luck. Below is the Json response: ({ "c ...

What is the best way to activate an API call in a React Modal only when the Modal is displayed

I have been assigned a project to create a proof of concept web application using REACT in my organization. The application includes a table displaying various issues, with each issue having a button that, when clicked, opens up a modal. The modal then fet ...