What is the best way to eliminate properties from multiple objects that are not undefined?

When attempting to remove properties from an object, it may throw an error if the property does not have a value. What is the correct method to delete similar properties from multiple objects?

Main.js

if (data.details.primary.transactionHistory !== undefined ||
   data.details.secondary.transactionHistory !== undefined) {
   delete data.details.primary.transactionHistory;
   delete data.details.secondary.transactionHistory;
}

Answer №1

To ensure the proper execution of your code, make sure to use the AND condition instead of OR. By switching from || to &&, the delete operation will only be triggered if both conditions are true.

if (data.details.primary.transactionHistory !== undefined &&
                        data.details.secondary.transactionHistory !== undefined) {
                        delete data.details.primary.transactionHistory;
                        delete data.details.secondary.transactionHistory;
                    }

Note: If dealing with nested objects, it is advisable to check properties step-by-step as shown below:

if (data.details && data.details.primary && data.details.primary.transactionHistory !== undefined) {
  delete data.details.primary.transactionHistory
}

This approach ensures that even if primary is not a property of details, your code will still function without errors. Feel free to adjust and simplify as needed.

Answer №2

It's puzzling why there is a need to verify if transactionHistory is not undefined

Consider this alternative approach:

const details = data.details;

if (details) {

  if(details.primary) {
    details.primary.transactionHistory = null;
    // or
    delete details.primary.transactionHistory;
  }

  if(details.secondary) {
    details.secondary.transactionHistory = null;
    // or
    delete details.secondary.transactionHistory;
  }

}

This method will essentially accomplish the same objective as your current implementation.

Answer №3

If you find yourself repeating this task often, it's a good idea to create a more general function for it:

function removeKeysFromObjects(objects, keys) {
    objects.forEach(obj => {
        keys.forEach(key => {
            try {
                let splitKey = key.split('.');
                let propToDelete = splitKey.pop();
                let objectHost = splitKey.reduce((acc, currentKey) => acc[currentKey], obj);
                delete objectHost[propToDelete];
            } catch (error) {}
        });
    });
    return objects;
}

console.log(
    removeKeysFromObjects([{a: {b: 5}}, {z: 3, b: {} }, {c: 8}], ['a.b', 'c'])
);

Answer №4

If you're looking to remove the transactionHistory in a more general manner without having to create individual if-statements for every nested object within data.details, you can use this approach:

// Sample data
let data = {
  details: { 
    primary: { transactionHistory: 'blah' }, 
    secondary: { transactionHistory: 'blah', someOtherProp: 'still here' },
    nohistory: {},
    miscproperties: { shouldNotBeDeleted: true }
  }
}

// Deleting transactionHistory from data
Object.keys(data.details).map((item) => { delete data.details[item].transactionHistory })

console.log(data)

You can include any necessary conditions within the curly braces if needed.

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

What is the best way to dynamically adjust the width of multiple divisions in Angular?

I am currently working on an angular project to create a sorting visualizer. My goal is to generate a visual representation of an array consisting of random numbers displayed as bars using divisions. Each bar's width will correspond to the value of th ...

Struggling to get Tailwind typography to play nice with a multi-column React application shell

I'm currently working on a React application with TypeScript and trying to integrate one of Tailwind's multi-column application shells (this specific one). I want to render some HTML content using Tailwind Typography by utilizing the prose class. ...

Error: React JS is unable to access the property 'path' because it is undefined

Currently, I am encountering an issue while setting the src of my image in React to this.props.file[0].path. The problem arises because this state has not been set yet, resulting in a TypeError: Cannot read property 'path' of undefined. To provid ...

Store the data from the form into the database according to the radio button choice

I feel like a fish out of water here...freshly dipping my toes into the ASP.net world, but finding it quite fascinating so far. Let me begin at the starting line: Background: I am currently working on an ASP.net MVC5 application that involves user login ...

Angular 2 routing for dynamic population in a grid system

My website is compiling correctly, however, in the Sprint dropdown menu where I have set up routing... <a *ngFor = "let item of sprint;" routerLink = "/Summary" routerLinkActive = "active"> <button *ngIf = "item.Name" mat-menu-item sty ...

How to implement ngx-infinite-scroll in Angular 4 by making a vertically scrollable table

Looking for a way to make just the table body scrollable in Angular 4 using ngx-infinite-scroll. I've tried some CSS solutions but haven't found one that works. Any help or documentation on this issue would be greatly appreciated. I attempted th ...

Utilizing Node.js for Lambda Functions

I am attempting to retrieve a list of all EC2 instances in a specific region using a lambda function. Below is the code snippet I am using: const AWS = require('aws-sdk'); AWS.config.region = '******'; exports.handler = async function( ...

What is the best way to delete a specific date from local storage using Angular after saving it with a key

I'm attempting to clear the fields in my object (collectionFilter) from local storage using localStorage.removeItem('collectionFilter'). All fields are removed, except for the date fields. Please note that I am new to JavaScript and Angular. ...

Combining nested Observables within an outer array without using inner subscribe (RxJS)

Looking at the TypeScript functions below, which are used for async HTTP-Calls: public retrieveAllMembersIdsFromGroup(groupId: string): Observable<string[]> public retrieveMember(memberId: string): Observable<Member> How can these be combined ...

Having trouble accessing variable values within the nth-child selector in JavaScript

I am attempting to utilize the value of a variable within the element selector p:nth-child(0). Instead of hardcoding the number as 0, I want to dynamically assign the value of a variable. In this case, the variable is represented by i in a for loop. Howev ...

Struggling to retrieve the value from ng-model?

Currently, I am utilizing this account due to being logged into Facebook on my other account and not having access to my phone for the verification code process. On another note, I am struggling to retrieve the value from an ng-model despite numerous atte ...

Is there a way for me to duplicate a complex element multiple times within the same page?

As an illustration, let's say I have a social tab located in my header that I would like to duplicate in the footer. This tab is comprised of various buttons with SVG images on top, event listeners linked to button IDs, and CSS styling. One option is ...

Content from PHP's unlink() function continues to persistently display

I run an Angular front end along with a PHP back end for my website. I utilize PHP's unlink function to remove specific images from Angular's assets folder: $fileToDelete = "../src/assets/images/".$name; unlink($fileToDelete) or die("Error delet ...

Styling text in JavaScript and CSS with colored fonts and underlines

I am looking to customize the CSS for the font style. <div id="a" onmouseover="chbg('red','b')" onmouseout="chbg('white','b')">This will change b element</div> <div id="b">This is element b</div ...

Angular8's NgFor directive is designed to bind to Iterables like Arrays only

Having an issue retrieving data from Github and displaying it, as I am encountering errors. The code editor is highlighting an error with "followers" in the github-followers.component.ts file. githup-followers.component.html <div *ngFor="let follower ...

Tips for discreetly recording information without disrupting normal workflow until necessary

Every 100-200 uses, I encounter a strange bug that I just can't seem to reproduce consistently. It's not a top priority to fix, but I would like to address it. To investigate further, I would need to scatter about 30 console.log statements throu ...

What are the steps to utilize an npm package effectively?

Although I have a great appreciation for npm and nodejs, I am struggling to understand css, let alone JavaScript. I know that this is a big part of the problem. My main question is: when I use npm to install a package, how can I Find ALL available comma ...

Enabling ng-disabled within an ng-repeat loop

I'm facing an issue with a form that is nested inside an ng-repeat directive. The form should only be enabled if a specific field (in this case a select dropdown) is selected, but for some reason, it's not working as expected. Can anyone provide ...

What's the most efficient method of exporting modules along with their submodules in (Vue, React)?

Looking for the most efficient method to export a module that contains submodules with the help of an index.js? I have been following a specific naming and saving convention for my web components in projects involving Vue or React. However, I am interested ...