Deleting items from objects within a JavaScript multidimensional array

I have encountered an issue while attempting to solve this problem. Despite reviewing various solutions provided here, I am consistently facing an error related to the pop() method.

The situation involves handling a multidimensional array in JavaScript where I need to remove sensitive information (e.g., Social Security Numbers) and return the modified array.

My initial strategy involved utilizing a foreach loop and the pop() function to eliminate the SSN element from each child array.

However, upon testing the code using Node in the command line, I kept getting an error message stating that element.pop() is not recognized as a function. I attempted alternatives like pop(), slice(), and filter(), but none of them worked successfully.

Upon running $> node filename.js,

H:\Apache2\htdocs\test\filename.js:50 noppi[i] = element.pop(); ^

TypeError: element.pop is not a function

let recs = [
    {
        ID: 1,
        NAME: 'John',
        EMAIL: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c8a2a7a0a688adb0a9a5b8a4ade6aba7a5">[email protected]</a>',
        SSN: '123'
    }, {
        ID: 2,
        NAME: 'Sally',
        EMAIL: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9aab8b5b5a099bca1b8b4a9b5bcf7bab6b4">[email protected]</a>',
        SSN: '456'
    }, {
        ID: 3,
        NAME: 'Angie',
        EMAIL: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c434a44486d48554c405d4148034e4240">[email protected]</a>',
        SSN: '789'
    }
];

let i = 0;
let noppi = [];

recs.forEach(element => {
    noppi[i] = element.pop();
    i++;
    
});

console.log(noppi);  

Answer №1

To avoid repetition, I will briefly summarize what has already been mentioned in the previous responses.

It is important to note that the input data structure is not a multi-dimensional array [ [ ... ], [ ... ] ], but rather an array of objects [ {...}, {...} ]. Therefore, Array methods like .pop() cannot be used directly on objects {...}.

A simple solution involves using .forEach() along with the delete operator.

recs.forEach(obj => delete obj.SSN)

The purpose of the delete operator is to remove a specific property from an object, such as SSN: '123-45-6789'. It is a straightforward and effective method for this task.

Keep in mind that .forEach() mutates the original array, meaning that the changes are made directly to the initial data (refer to Minja's comment).

let recs = [
    {
        ID: 1,
        NAME: 'John',
        EMAIL: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="402a2f282e002538212d302c256e232f2d">[email protected]</a>',
        SSN: '123'
    }, {
        ID: 2,
        NAME: 'Sally',
        EMAIL: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3d1dcdcc9f0d5c8d1ddc0dcd59ed3dfdd">[email protected]</a>',
        SSN: '456'
    }, {
        ID: 3,
        NAME: 'Angie',
        EMAIL: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="50313e373935103528313d203c357e333f3d">[email protected]</a>',
        SSN: '789'
    }
];

recs.forEach(obj => delete obj.SSN);

console.log(recs)

Answer №2

Give this a shot:

records.forEach(item => {
    itemsList.push = item;
});

Attempting to apply pop() method to an object that is not an array.

Answer №3

If you require the removal of SSN from your data object, consider using the following code snippet which should meet your needs:

records.forEach(item => {
 const { SSN, ...otherData } = item;
    updatedRecords.push(otherData);
});

In this example, we are extracting and excluding the SSN field from the object, then pushing the remaining data into a new array named updatedRecords.

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

Checking for an exact value using the includes() method in JavaScript - a comprehensive guide

In order to populate checkboxes based on a string delimited with pipes, I have been using the includes() method. However, I am encountering an issue where items with similar names are both marked as true because they share the same string, even if they are ...

A server-side rendered page in Next.js that functions without the need

Hey everyone, I'm curious about the best way to serve an HTML page in a Next Js application without relying on additional JavaScript. I need this because I want to make sure my webpage can be accessed by users who have older phones like Symbian or oth ...

Identifying a user's unique identity through a POST request using Node.js

Currently, I am developing a browser game that integrates voice communication. To capture audio within the browser, I have chosen to use wami-recorder. This tool relies on Flash technology to make a POST request to the server containing the recorded audio. ...

Create a unique command that will run regardless of the success or failure of the command before

Even if a preceding command fails, the end command is still executed. For example: browser.waitForElementIsVisible("non-existing-item", 500).end() I am looking to create a custom command that always gets called in the same way as the end command. When I t ...

Preventing v-stepper-step header click in Vuetify.js when form is invalid

I'm using Vuetify's v-stepper component. What I'm trying to achieve is: When a user clicks on a stepper step in the header, I want to block the click event if the active form is not valid. I have been able to accomplish this by attaching ...

Steps for Verifying the Legitimacy of an AJAX Request

In the process of creating a website where users are required to solve puzzles quickly, I am utilizing JavaScript to track the time taken for each puzzle. However, I am concerned about the possibility of users manipulating this data before it is sent to th ...

Resultant vector

Having trouble calculating the resultant of 3 vectors. Every time I input a number, it returns NaN. Can someone shed some light on this? var vector1 = document.getElementById("f1"); var vector2 = document.getElementById("f2"); var vecto ...

Unlocking the Controller Action: Navigating from a Component Controller in Ember

I am currently trying to enhance the functionality of an Ember component. The specific component I am working on is located here: app / templates / programmers.hbs {{echo-hlabel-tf id= "id-test-hlabel" class="class-test-hlabel-mio" label="Horiz ...

Bug in toFixed causing incorrect results

function calculateTaxAndTotalRent(rent) { var phoneCharges = parseFloat($('#phone_charges').val()); phoneCharges = phoneCharges.toFixed(2); rent = parseFloat(rent); rent = rent.toFixed(2); var tax = parseFloat((rent * 15) / 1 ...

Ensuring continuous user login during webpage refreshes with the help of React and local storage

Currently, I am working on implementing the use of local storage to ensure that upon refresh, the user remains logged in rather than being signed out each time. Successfully, I have been able to store data in local storage by utilizing the following code ( ...

Count Comparisons in Insertion Sort Algorithm - C++

Currently, I am involved in a project that requires the implementation of various sorting algorithms along with counter variables to measure runtime for different array sizes. However, my output for insertion sort is not aligning with the expected output. ...

What is the most effective way to populate a numpy ndarray by invoking a function for every row and column?

I am looking to generate a numpy ndarray by defining the values using a function of row and column. For example, I envision something like this (the syntax is incorrect, but you can understand the concept): >>> np.ndarray((2,3), lambda r,c: 3*r+ ...

Handle Ajax requests to prevent multiple submissions upon clicking

Seeking a solution to avoid multiple requests when the user clicks on the login or register button. The code provided below is not functioning as expected; it works fine the first time but then returns false. $('#do-login').click(function(e) { ...

What could be causing webpack to struggle in locating the loader?

Check out my package.json: { "name": "redux-todo", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "webpack-dev-server" }, "devDependencies": { "babel": "^6.5.2", "babel-loader": "^6.2.5", "bab ...

Exporting data from AngularJS to Excel is not functioning correctly in Internet Explorer. Additionally, the exported Excel file does not display properly in Firefox and

I have been attempting to Export a table from a jsp page to Excel using AngularJs. Is Angularjs not compatible with IE? I am also encountering this error SCRIPT5009: 'Node' is undefined In Chrome and Firefox, the Excel file only opens when save ...

Error: NS_ERROR_CORRUPTED_CONTENT encountered while running a Live Server with TypeScript-generated JavaScript files

Currently, I am working on creating a straightforward banking website using vanilla TypeScript, HTML, and CSS. My plan is to integrate the Plaid API later on to conduct operational tests. To get started, I am testing the project structure locally using Liv ...

The functionality of the Eslint object-property-newline feature is not functioning as expected

Within my configuration file .eslintrc, I have set "object-property-newline": ["error", { "allowAllPropertiesOnSameLine": true }], and "max-len": "off". However, objects like const something = {a: 5, ffsdfasdasdsddddd: 'asdasdasdddddddddddssssssddddd ...

Enhancing socket.io with the incorporation of a variable

I was looking for a way to connect an object named player to various sockets. My initial approach was to simply do socket.prototype.player = whatever; However, no matter what I attempt to prototype, it always returns undefined. Does anyone have a solution ...

Using multiple images to create a visual in three.js

Looking to create a unique shape or maybe even a word using three.js by incorporating various pictures. Take, for example, the following image: https://i.sstatic.net/9O1dF.jpg My plan is to determine the points that will form the desired shape and then p ...

Issue with React / Express failing to route links accurately

Currently, my React project is functioning well except for Express. I have been struggling to find comprehensive tutorials on implementing correct routing with Express in a MERN stack application. I have come across some Stack Overflow posts, but none of ...