Keep only certain fields and eliminate the rest

Write a function that filters out all fields except 'firstName' and 'lastName' from the objects.

Check out this code snippet I came up with. Any feedback?

let people = [
    {
        firstName: 'John',
        lastName: 'Clark',
        gender: 'male'
    },
    {
        firstName: 'Kaily',
        lastName: 'Berserk',
        gender: 'female'
    },
    {
        firstName: 'Steven',
        lastName: 'Bergeron',
        gender: 'male'
    }
];

function filterNamesOnly(arr) {
    let first = 'firstName';
    let last = 'lastName';

    return arr.forEach(person => {
        for (const key in person) {
            if (key !== first && key !== last) {
                delete person[key];
            }
        }
    })
}

console.log(filterNamesOnly(people));
console.log(people);

Answer №1

The function has two parameters - the arr parameter representing the array and the names parameter indicating the fields to keep.

arr refers to the input array while names lists the specific fields to be preserved within the array.

The process involves utilizing the forEach method twice; once for iterating through each element in the arr and then again for accessing the keys within each object of the array. This allows pinpointing the exception names that correspond to specific fields in the array of objects.

let people = [
    {
        firstName: 'John',
        lastName: 'Clark',
        gender: 'male'
    },
    {
        firstName: 'Kaily',
        lastName: 'Berserk',
        gender: 'female'
    },
    {
        firstName: 'Steven',
        lastName: 'Bergeron',
        gender: 'male'
    }
];

function removeAllExceptNames(arr, names) { // The 'arr' remains unchanged, while 'names' specifies the desired field names
  arr.forEach(a => {
    Object.keys(a).forEach(b => {
      if (!names.includes(b)) { delete(a[b]) }
    })
  })
}

removeAllExceptNames(people, ["firstName", "lastName"]);
console.log(people);

Answer №2

If you want to achieve the desired output, you can utilize a combination of map and Object.fromEntries:

const people = [ { firstName: 'John', lastName: 'Clark', gender: 'male' }, { firstName: 'Kaily', lastName: 'Berserk', gender: 'female' }, { firstName: 'Steven', lastName: 'Bergeron', gender: 'male' }];

const keepProperties=(arr, properties)=>arr.map(obj=>Object.fromEntries(properties.map(prop=>[prop,obj[prop]])));

console.log(keepProperties(people, ['firstName','lastName']))

Answer №3

Understanding the functionality of the keyword delete is essential. According to the Mozilla Foundation,

The JavaScript delete operator eliminates a property from an object; once all references to that property are removed, it will be automatically released.

In this particular case, you have successfully deleted the reference, but the list remains unordered. It simply gets replaced with undefined. To achieve proper removal and reordering, we can use the splice array function. This function removes the element and rearranges the remaining items accordingly.

function removeAllExceptNames(arr,firstName,lastName) {
     let instancesOfNamesInArray = arr.filter(e => e.firstName == firstName || e.lastName == lastName);
     // Iterate through these instances and remove them from the array
     instancesOfNamesInArray.foreach((item) => {
          arr.splice(arr.indexOf(item),1); // This will delete the item from the array
     });
}

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

Locating the present URL, dividing it into segments, and verifying the presence of "index.php" within the URL

I'm currently struggling with extracting the current page URL, splitting it into parts, and then checking for the presence of the "index.php" phrase. Here's what I have attempted so far: <?php $domain = $_SERVER['REQUEST_URI']; $val ...

Triumph awaits before the final response is delivered

Being new to web development, I am currently working on my first web application using purely node.js. In the registration process, form data is sent from the client-side to the server and then stored in the database. Upon a successful response, the client ...

Triggering jQuery Submit Form when Form is Modified

I need help with automatically submitting a form using jQuery when an input changes. The specific input I am working with is a date picker, and I want the form to be submitted as soon as a user makes a selection. <form id="select_date" name="select_da ...

Eliminating null values from a multidimensional array

Is there a way to remove the array elements cctype, cctypologycode, and amount if they are empty? What would be the most efficient approach? { "ccInput": [ { "designSummaryId": 6, "CCType": "A", "CCTypologyCode": "A", "Amount ...

socket.io establishes several sockets for each connection

At times, when the server is experiencing some load, connecting to the page may result in multiple sockets being created. If there is significant lag, the connection may never be established while additional sockets are generated every second indefinitely. ...

What is the best way to change a date from the format DD/MM/YYYY to YYYY-MM-DD

Is there a way to use regular expressions (regex) to convert a date string from DD/MM/YYYY format to YYYY-MM-DD format? ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Utilizing d3.js to implement a scatterplot with zoom functionality that focuses solely on zooming the axis without affecting

Having trouble creating a scatterplot with zoom functionality where only the axis is getting zoomed, not the data itself. Can anyone provide some assistance or insight on what might be wrong? If you're interested in checking out the project, here&apo ...

Performing subtraction on two arrays in Javascript

Is there a way to eliminate all duplicate elements from one array list that are also present in another array list using the .filter() method of ES6 javascript? I am open to solutions in jQuery as well, but they must be compatible with IE11+ and Chrome fo ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

The alignment of the Slick slider item appears off-center when viewed on a mobile device

https://i.stack.imgur.com/kwxaX.png When viewing the items on a mobile device, they are not centered as desired. The issue lies with the first item not being displayed in the center. How can this problem be addressed? Here is the code snippet: slickOptio ...

Utilizing Javascript to Open a New Tab from Drupal

I'm attempting to trigger the opening of a new tab when a specific menu link is clicked within a Drupal website. My initial approach was to incorporate JavaScript directly into the content of the page, but unfortunately this method has not been succes ...

Develop a library of components using TypeScript and Less files

I'm currently in the process of creating a React UI library that will consist of various components such as Buttons, Inputs, textareas, etc. This library, which I've temporarily named mylib, will be reused across multiple projects including one c ...

Issue with displaying error message on span element during validation

Is there a way you can recommend for displaying the error message within element with id #genderError instead of after it? errorPlacement: function(error, element) { if (element.attr("name") == "myoptions" ) error.appendTo('#genderError'); ...

The play button in the customized React AudioPlayer may sometimes need to be tapped twice in order to start

I've encountered an issue with my simple audio player (React/Vite) that transitions to the next track automatically or manually. Everything seems to be functioning correctly except for the initial press of the play button. The player opens with the pa ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

Combine several dictionary values under a single dictionary key in JavaScript

I have a unique dictionary structure displayed below. My goal is to populate it with values in a specific way. It all begins here var animals = { flying : {}, underground : {}, aquatic : {}, desert : {} }; To illustrat ...

Unable to get jQuery waypoints to function on local server

Currently, I am working with jQuery. I downloaded an example shortcut for infinite scroll from jQuery Waypoints and tried to use it. However, when the page reaches the end, the web console displays the following error: XMLHttpRequest cannot load file:// ...

React components are failing to display data as expected

I need to display certain data based on the id provided in the url. When I use console.log() with res.json, I can see the data but I'm unsure how to pass it to the 'articleComponent'. const Articles = () => { const query = (id) => ...

Issue with passing reactive property to component in Vue 3 application

I am currently working on a Vue 3 application and I am in the process of setting up a store for state management. Within this application, I have several important files that play different roles: app.vue component.vue main.js store.js These files contai ...