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

Issue uploading with Candy Machine Version 2/ complications with directory

For some reason, I am encountering issues with the upload operation. Switching from relative to absolute paths did not resolve the error, and using the -c flag for the directory containing images and JSON files is causing a problem. However, other flags ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...

What is the best way to display the data model in Angular as HTML?

I am facing an issue with my data-model where it needs to be converted or displayed as HTML, but currently it is only appearing as plain text. Here is the HTML code snippet: <div ng-repeat="item in ornamentFigures" class="ornament-item"> <la ...

Uploading files to an S3 bucket with Node.js

Currently, I am utilizing Sailsjs version 0.12.1 along with node.js 4.2.6 My objective is to upload a file from the front-end (built using angular.js) through an API and then proceed to upload this file to an AWS S3 bucket from the backend. When sending ...

React Chart.js allows for consistent spacing for x-axes by displaying dates in a well-organized

After incorporating displayFormats in scales.x, I noticed that my xAxes labels are spaced differently based on the data object they contain. How can I adjust my xAxes labels to have equal spacing? The code snippet is displayed in the following image. Pleas ...

Passing a node.js variable to an ejs template through a post request

In my nodejs application, I utilize Express JS to handle post requests. Within the INDEX.JS FILE, the following code snippet is present: this.app.post('/profile', (req, res, next) => { let password = req.bo ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

What could be the reason for my onChange event not functioning properly?

The issue I'm experiencing involves my onchange event not properly copying the text from the current span to the hidden field. Any ideas on why this might be happening? Check out my code at this link. ...

Showing arbitrary text on Vue.js template

In my Vue.js application, I have a Loader component that randomly displays one of several messages. Here is how I implemented it: Vue.component('Loader', { data() { const textEntries = [ 'Just a moment', ...

Having trouble retrieving information from .pipe(map()) method

Encountering some issues with Observable handling. I have a function that returns an Observable. public getData(userId) { const data = this.execute({userId: userId}); return {event: "data.get", data: data} } private execute(input: SomeDt ...

Adjustable Cursor - modify size while in motion at high speeds

I've designed a unique custom cursor and I am looking to enhance its functionality by adjusting its scale dynamically during fast movements. Similar to the cursor on this website: Example.com Here is my custom cursor for reference: CodeSandBox What ...

Request a HTML variable and send it to JavaScript

My latest project involves a Binary to Decimal Calculator that is now fully functional, but I am looking to integrate an HTML input into it. <html> <input placeholder="00000000" name="htmlinput"></input> <input id="clickMe" type="butt ...

Experience the magic of a customized cursor that disappears with a simple mouse movement in your website,

I have been experimenting with designing a custom cursor for my website. After finding a design I liked, I made some adjustments to suit my needs. However, an issue I encountered is that when I scroll, the custom cursor also moves away from its original po ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

What is the most efficient way to prevent duplicate items from being added to an array in a Vue 3 shopping cart

I currently have a functional shopping cart system, but I am facing an issue where it creates duplicates in the cart instead of incrementing the quantity. How can I modify it to only increment the item if it already exists in the cart? Also, I would like t ...

Error: JSON parsing failed due to an unexpected token 'S' at position 17

Trying to troubleshoot a syntax error in JSON.parse() within a product warranty registration process. Transitioning from Java to AngularJS for this project, I have an API built in PHP handling the back-end operations and a controller managing communication ...

Encountered an issue while trying to register a service worker: "[ERROR] Cannot import statement outside

With the utilization of register-service-worker, the boilerplate for registerServiceWorker remained untouched. /* eslint-disable no-console */ import { register } from 'register-service-worker'; if (process.env.NODE_ENV === 'production&ap ...

Setting up Next.js configuration for JSX file type

I have developed a Next 13 application and installed the package @viral-loops/widgets. However, upon running the application, I encountered the following error: error - ./node_modules/@viral-loops/widgets/dist/react/Widget.jsx Module parse failed: Unexpec ...

JavaScript function trying to send a POST request to API

I'm encountering an issue when attempting to execute an API GET request using JavaScript's built-in XMLHttpRequest function. I'm perplexed by why this functionality is failing to operate properly. function getStats(username){ const request ...

Analyzing - Dynamically Tagging Method - Implementing direct call regulations- Erase enduring variables

https://i.sstatic.net/elGJz.jpg Hello there, I am currently utilizing a Direct call rule within DTM. When I click on a href link that opens in a new window, I want to remove or clear the eVars and events associated with the click. I have implemented custo ...