What is the best method for converting an Object with 4 properties to an Object with only 3 properties?

I have a pair of objects:

The first one is a role object with the following properties:

Role {
    roleId: string;
    name: string;
    description: string;
    isModerator: string;
}

role = {
    roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1",
    name:"HR",
    description:"HR of the Company",
    isModerator:"N"
}

And the second object is roleDetails with these properties:

RoleDetails {
    name: string;
    description: string;
    isModerator: string;
}

I need to make roleDetails = role; So that when I console.log(roleDetails), I would receive:

roleDetails = {
    name:"HR"
    description:"HR of the Company"
    isModerator:"N"
}

Answer №1

To declare the type RoleDetails, you can utilize the Omit<Type, Keys> function to omit specific keys

  • For example, in this scenario, excluding the key roleId

Here is the code snippet:

interface Role {
  roleId: string;
  name: string;
  description: string;
  isModerator: string;
}

type RoleDetails = Omit<Role, 'roleId'>;

const role: Role = {
  roleId: '8e8be141-130d-4e5c-82d2-0a642d4b73e1',
  name: 'HR',
  description: 'HR of the Company',
  isModerator: 'N',
};

const roleDetails: RoleDetails = {
  name: role.name,
  description: role.description,
  isModerator: role.isModerator,
};

Answer №2

To simplify, you can assign each property individually (please also note that I've included , in the original object between each value):

let category = {
  categoryId: "4c6f1da0-09ac-45f5-a352-afd7d513a632",
  name: "Technology",
  description: "Tech Industry",
  isActive: "Y"
};

let categoryDetails = {
  name: category.name,
  description: category.description,
  isActive: category.isActive
};

console.log(categoryDetails);

You can also achieve this dynamically using an array of keys:

let category = {
  categoryId: "4c6f1da0-09ac-45f5-a352-afd7d513a632",
  name: "Technology",
  description: "Tech Industry",
  isActive: "Y"
};

let keys = ["name", "description", "isActive"];

let categoryDetails = Object.entries(category).reduce((a, [k, v]) => {
  if (keys.includes(k)) a[k] = v;
  return a;
}, {});

console.log(categoryDetails);

Additionally, you can exclude specific keys by using an array of keys to exclude:

let category = {
  categoryId: "4c6f1da0-09ac-45f5-a352-afd7d513a632",
  name: "Technology",
  description: "Tech Industry",
  isActive: "Y"
};

let keysToExclude = ["categoryId"];

let categoryDetails = Object.entries(category).reduce((a, [k, v]) => {
  if (!keysToExclude.includes(k)) a[k] = v;
  return a;
}, {});

console.log(categoryDetails);

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

Troubleshooting a JavaScript error: Script.js throwing 'Uncaught TypeError' at line 5

While working on a small project, I encountered a JavaScript error that reads: script.js:5 Uncaught TypeError: Cannot set properties of null (setting 'onkeyup') at script.js:5:18 Below is the HTML & JavaScript code snippet that triggered thi ...

Trouble arises with MySQL query in PHP/jQuery setup

I am currently in the process of developing a user panel where users can change their first and last names. Everything seems to be working fine with the $ajax form handling, as I can use console.log(data) and see {fname: "Damian", lname: "Doman", id: "20" ...

React Modals: Only the modal component triggered by the first click will open, with no other modals opening

As a newcomer to StackOverflow, I apologize if my problem description is not clear. I am currently learning React and working on a course-search app as a project. The app filters courses based on user input from a JSON file and displays them in cards with ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Is it possible to use a component created in the newest version of Angular in apps developed with older versions of Angular?

I am interested in developing a component using the most recent version of Angular. However, my intention is to use this component in two distinct Angular applications - one created with Angular 6 and another with Angular 10. Is it feasible to achieve this ...

What steps should be taken to avoid an event from occurring when an error message is encountered?

I have a dropdown list of cars where an error message is displayed if any of them becomes inactive. When the error message is shown, clicking on the Route Car button should prevent any event from occurring, i.e., no modal popup should be displayed. How ca ...

Vue paginated select with dynamic data loading

My API has a endpoint that provides a list of countries. The endpoint accepts the following query parameters: searchQuery // optional search string startFrom // index to start from count // number of options to return For example, a request with searchQu ...

Extracting user login details from a Java script-based web browser for a RASA chatbot

Our website integrates a web bot using Javascript. When users log in, they can access the chatbot icon. Currently, the chatbot starts without collecting user data. However, having user data is important as we plan to trigger actions based on user ID. If ...

Why is the radio button not chosen in the ns-popover popup? The radio button is only selected in the popup of the last column

In my Angular controller, I am trying to set the radio model but it is only appearing in the last column popup of the table. The ns-popover is displayed when clicking on a table column. Here is the Angular Code: var app = angular.module('app', ...

Encountering the error 'node' getProperty of undefined while trying to retrieve data from an array stored in my state variable

Hello, I am currently developing an app that retrieves images from Instagram using axios. I have successfully stored the image files in an array named 'posts' within my state. Looping through this array to display each image is not an issue for m ...

What is the best way to incorporate a button that can toggle the visibility of the sidebar on my post page?

Check out this post of mine I noticed a button on someone's page that could hide their sidebar and expand it again when clicked. How can I implement this feature? Is it a simple task? ...

Using Codeception's selenium module to wait for JavaScript and Ajax requests to

I am currently facing an issue where I need to wait for an ajax call to finish loading before moving on to the next step. I have tried using the waitForJS function, but I am struggling with building the JavaScript condition. I have experimented with diffe ...

Methods for applying multiple styles within a div using the Document Object Model

Is there a way to add multiple style attributes using DOM `setAttribute` in JavaScript? I've tried doing it but it doesn't seem to work. Can someone provide guidance on how to achieve this? var modify = document.getElementById('options&apo ...

Limit the range of potential inputs for the function parameter

class Coordinate { constructor(readonly x: number, readonly y: number) {} } const Up = new Coordinate(0, -1); const Right = new Coordinate(1, 0); const Down = new Coordinate(0, 1); const Left = new Coordinate(-1, 0); // How can we restrict the directio ...

Avoid the need to refresh the HTML content every time there is a change in the Angular $

One of the challenges I'm facing is with a for loop in my JavaScript: for (var i=0;i<2;i++) { $scope.widget = widgets[i]; $scope.header = widgets[i].data.header; $scope.items = widgets[i].data.items; $scope.footer = widgets[i].data ...

Utilize Javascript/Jquery to categorize JSON data based on the days of the week (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)

A function is provided below that retrieves data for a chart. The output produced by this function is structured as follows: [Object { date=Date, value=112, volume=1469}, Object { date=Date, value=124, volume=539}, Object { date=Date, value=114, vo ...

What is the best way to manage undefined status in react after the user chooses to cancel selecting a file?

Having an issue with my simple Input file type in React. I'm storing the selected file in state, but when I click the clear button, the state doesn't actually get cleared. This leads to {selectedFile.name} throwing an undefined error if the user ...

Incorporating a variety of classes by utilizing loops

Looking to add a class to specific li elements - the 1st, 4th, and 7th, the 2nd, 5th, and 8th, and the 3rd, 6th, and 9th. Is this possible? Is there a way to achieve this? ...

DreamFactory's REST API POST request for rest/user/session consistently encounters errors in Internet Explorer 9

In Firefox, Chrome, and Safari, the initial POST rest/user/session request works perfectly fine. However, in Internet Explorer 9, it consistently returns an error. When the dataType is specified as "json," IE9 encounters a 'no transport' error w ...

Exploring face detection with Three.js

When I utilize an octree, I am able to generate an array of faces that are in close proximity to an object. However, I am unsure how to perform a ray cast to these faces. All the resources I have found only explain how to ray cast to a mesh, line or poin ...