Drop items next to the specified keys. Vanilla JavaScript

I am trying to create a new array of objects without the gender field. Can you identify any mistakes in my code?

let dataSets = [
    { name: "Tim", gender: "male", age: 20 },
    { name: "Sue", gender: "female", age: 25 },
    { name: "Sam", gender: "male", age: 30 }
  ];
  let newArray = dataSets.slice();
  let utilities = {
    filterFields: function () {
      let argumentsArr = [].slice.call(arguments);
      for (let i = 0; i < newArray.length; i++) {
        for (let key in newArray[i]) {
          for (let j = 0; j < argumentsArr.length; j++) {
            if (key !== argumentsArr[j]) {
              delete key;
              return newArray;
            } 
          } 
        } 
      } 
    } 
}; 
const results = utilities.filterFields("name", "age");// specify fields to keep

console.log(results);

Answer №1

To eliminate a specific property, you may consider developing an omit() function.

The utilization of Array.map() allows us to apply this function to each element in the array:

let datasets = [ { name: "Tom", gender: "male", age: 12 }, { name: "Becky", gender: "female", age: 11 }, { name: "Huck", gender: "male", age: 13 } ];

function omit(obj, field) {
    return (({ [field]: _, ...result }) => result)(obj);
}

let updatedDatasets = datasets.map(person => omit(person, 'gender'));
console.log('Updated datasets:', updatedDatasets);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

One way to achieve this is by utilizing the map method:

const updated_array = collections.map(item => {
    return {title: item.title, year: item.year};
})

The above code snippet demonstrates how a new array can be generated with objects missing the gender key.

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

Tips on retrieving and showcasing information from various endpoints in React?

I am working with two different endpoints and I need to fetch data from both simultaneously in order to display it in one single element. For example, I want to show data from one table along with the corresponding name from another table if the product id ...

Tips for dynamically passing parameters to functions in JavaScript?

Looking for a solution to dynamically receive input from the user in my function: divResize = { myDiv:function(width, height) {...} } divResize.myDiv(100,400); I want to make these numbers interactive and changeable based on user input. How can I achie ...

What are the benefits of keeping synchronous state in the Redux store?

Is it necessary to store non-async state in the Redux store? For instance, when dealing with a modal that simply shows or hides, is it worth the extra work to toggle it within the store? Wouldn't it be simpler to just keep it as local state in the Rea ...

swap between style sheets glitching

My website features two stylesheets, one for day mode and one for night mode. There is an image on the site that triggers a function with an onclick event to switch between the two stylesheets. However, when new visitors click the button for the first ti ...

When it comes to identifying a click outside of an element, the Jquery or Javascript function may encounter some challenges specifically with Internet Explorer

After reviewing various solutions online, I noticed that they all function properly on Chrome and Firefox but encounter issues with Internet Explorer when interacting with an SVG. For instance, consider the following code snippet: $(document).on("click",( ...

Issue encountered when AngularJS struggles to evaluate regular expression within ng-pattern

Currently, I am implementing the ng-pattern argument in an input text field to restrict input to only numeric values: <input type="text" ng-model="numericField" ng-pattern="/^[0-9]*$/" /> However, there seems to be an unusual behavior in the regex ...

What is the best way to add permissions to each role in JavaScript?

I have been attempting to dynamically add data to an HTML table using JavaScript. The data consists of roles and their corresponding permissions, which are retrieved using Laravel's ORM. I have tried utilizing a nested each jQuery function to append t ...

What is the best way to navigate from a button in NextJS to another page that I have built within the same application?

As I work on developing a website for a pet rescue charity using Next.js, I am facing an issue with getting my button or link to function correctly. Every time I try to navigate to another page within my Next.js app, I encounter a 404 error stating "This p ...

When trying to use routes with the .map() function, it does not seem

I am currently working on developing a multi-page web application using react-router-dom. However, I have encountered an issue with the user list page (userlist.js) where the data inside the .map() function is not being returned. Interestingly, the code pr ...

Replace HTML elements with AJAX and JavaScript

Working with MySQL data in pyramid presents a challenge as I need to dynamically change an HTML if statement based on the results from JS ajax calls. The main page receives data from views.py and passes it to the .mak script. The key views here are the ma ...

The attempt to create the property 'and_ff' on the string 'and_chr 89' has failed

Encountering an issue with a Lambda function, I receive an error that does not occur when running the same code within an Express app. I'm puzzled. Data returned by caniuse.getLatestStableBrowsers(); [ 'and_chr 89', 'and_ff 86& ...

Click on the next tab within the ExtJS tab menu

I am looking to deactivate a tab and if it happens to be active, I want the system to automatically switch to the next tab. I attempted myPanel.tab.disable(); if(myPanel.tab.active) myPanel.NextSibling().tab.setActive(); and myPanel.tab.disable(); ...

A guide on successfully transferring JSON Data to an Express REST API

Currently, I am in the process of developing a REST API with Node/Express and have a query regarding the setup of the API along with integrating a JSON file. As an illustration, the JSON data that I wish to reference consists of an ID number, model, and co ...

Connect a function to create a new document element in order to modify the

I am attempting to intercept document.createElement in order to modify the value of the src property for each assignment. My current approach involves: var original = document.createElement; document.createElement = function (tag) { var element ...

The contact form displays a confirmation message indicating successful submission, however, it fails to actually send the email

Having issues with a PHP script I created for the contact page on my website. After a user fills out and submits the form, they see a success message but the email is not sent. Can someone review this script and point out where I went wrong? <?php ...

What are the steps to develop a progress bar using PHP and JavaScript?

In the application I'm developing, PHP and JavaScript are being used extensively. One of my tasks involves deleting entries from the database, which is a time-consuming process. To keep the end-user informed, I would like to provide updates on the pr ...

Experiencing issues with autoungrabify or autolock in cytoscape.js?

I have been working on a web application using Cytoscape.js, and I recently integrated the Edgehandles extension to allow users to add edges. The two types of edges that can be added are undirected and directed. Adding directed edges is functioning as expe ...

Performing a Javascript ajax post of a canvas snapshot in "image/jpeg" format to an asp.net web form

Here is the JavaScript AJAX code snippet: var dataURL = canvas.toDataURL("image/jpeg"); var xhr = new XMLHttpRequest(); xhr.open("POST", "myPage.aspx", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechan ...

What is the best way to loop through a group of WebElements, and only log the results that contain a specific substring?

In my test case, I'm utilizing Mocha to handle the scenario. The test appears to be passing successfully, however, no logs are being printed... it('Is 'Mooooooo!!!! I2MaC0W' a Substring in Results?', function() { this.timeout(50 ...

How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet: $(document).ready(function () { $(".VociMenuSportG").each(function () { ...